package processor

import (
	"context"
	"time"

	"eslogad-be/internal/entities"
	"eslogad-be/internal/repository"

	"github.com/google/uuid"
)

type LetterActivityProcessor interface {
	LogActivity(ctx context.Context, letterID uuid.UUID, action string, userID uuid.UUID, details map[string]interface{}) error
	LogStatusChange(ctx context.Context, letterID uuid.UUID, fromStatus, toStatus string, userID uuid.UUID) error
	GetActivitiesByLetterID(ctx context.Context, letterID uuid.UUID) ([]entities.LetterOutgoingActivityLog, error)
}

type LetterActivityProcessorImpl struct {
	activityLogRepo *repository.LetterOutgoingActivityLogRepository
}

func NewLetterActivityProcessor(activityLogRepo *repository.LetterOutgoingActivityLogRepository) *LetterActivityProcessorImpl {
	return &LetterActivityProcessorImpl{
		activityLogRepo: activityLogRepo,
	}
}

func (p *LetterActivityProcessorImpl) LogActivity(ctx context.Context, letterID uuid.UUID, action string, userID uuid.UUID, details map[string]interface{}) error {
	log := &entities.LetterOutgoingActivityLog{
		LetterID:      letterID,
		ActionType:    action,
		ActorUserID:   &userID,
		Context:       details,
		OccurredAt:    time.Now(),
	}

	return p.activityLogRepo.Create(ctx, log)
}

func (p *LetterActivityProcessorImpl) LogStatusChange(ctx context.Context, letterID uuid.UUID, fromStatus, toStatus string, userID uuid.UUID) error {
	details := map[string]interface{}{
		"from_status": fromStatus,
		"to_status":   toStatus,
	}

	return p.LogActivity(ctx, letterID, "status_changed", userID, details)
}

func (p *LetterActivityProcessorImpl) GetActivitiesByLetterID(ctx context.Context, letterID uuid.UUID) ([]entities.LetterOutgoingActivityLog, error) {
	return p.activityLogRepo.ListByLetter(ctx, letterID)
}