package processor

import (
	"context"

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

	"github.com/google/uuid"
)

type LetterAttachmentProcessor interface {
	CreateAttachments(ctx context.Context, letterID uuid.UUID, attachments []entities.LetterOutgoingAttachment) error
	RemoveAttachment(ctx context.Context, letterID uuid.UUID, attachmentID uuid.UUID) error
	GetAttachmentsByLetterID(ctx context.Context, letterID uuid.UUID) ([]entities.LetterOutgoingAttachment, error)
}

type LetterAttachmentProcessorImpl struct {
	attachmentRepo *repository.LetterOutgoingAttachmentRepository
}

func NewLetterAttachmentProcessor(attachmentRepo *repository.LetterOutgoingAttachmentRepository) *LetterAttachmentProcessorImpl {
	return &LetterAttachmentProcessorImpl{
		attachmentRepo: attachmentRepo,
	}
}

func (p *LetterAttachmentProcessorImpl) CreateAttachments(ctx context.Context, letterID uuid.UUID, attachments []entities.LetterOutgoingAttachment) error {
	if len(attachments) == 0 {
		return nil
	}

	// Set letter ID for all attachments
	for i := range attachments {
		attachments[i].LetterID = letterID
	}

	return p.attachmentRepo.CreateBulk(ctx, attachments)
}

func (p *LetterAttachmentProcessorImpl) RemoveAttachment(ctx context.Context, letterID uuid.UUID, attachmentID uuid.UUID) error {
	return p.attachmentRepo.Delete(ctx, attachmentID)
}

func (p *LetterAttachmentProcessorImpl) GetAttachmentsByLetterID(ctx context.Context, letterID uuid.UUID) ([]entities.LetterOutgoingAttachment, error) {
	attachmentMap, err := p.attachmentRepo.ListByLetterIDs(ctx, []uuid.UUID{letterID})
	if err != nil {
		return nil, err
	}
	if attachments, ok := attachmentMap[letterID]; ok {
		return attachments, nil
	}
	return []entities.LetterOutgoingAttachment{}, nil
}