package processor

import (
	"context"
	"errors"

	"eslogad-be/internal/entities"

	"github.com/google/uuid"
)

type LetterValidationProcessor interface {
	ValidateCreateOutgoingLetter(ctx context.Context, letter *entities.LetterOutgoing) error
	ValidateUpdateOutgoingLetter(ctx context.Context, letter *entities.LetterOutgoing, existingLetter *entities.LetterOutgoing) error
	ValidateDeleteOutgoingLetter(ctx context.Context, letter *entities.LetterOutgoing) error
	ValidateApprovalSubmission(ctx context.Context, letter *entities.LetterOutgoing) error
}

type LetterValidationProcessorImpl struct{}

func NewLetterValidationProcessor() *LetterValidationProcessorImpl {
	return &LetterValidationProcessorImpl{}
}

func (p *LetterValidationProcessorImpl) ValidateCreateOutgoingLetter(ctx context.Context, letter *entities.LetterOutgoing) error {
	if letter.Subject == "" {
		return errors.New("letter subject is required")
	}

	if letter.CreatedBy == uuid.Nil {
		return errors.New("letter creator is required")
	}

	if letter.IssueDate.IsZero() {
		return errors.New("letter issue date is required")
	}

	return nil
}

func (p *LetterValidationProcessorImpl) ValidateUpdateOutgoingLetter(ctx context.Context, letter *entities.LetterOutgoing, existingLetter *entities.LetterOutgoing) error {
	if existingLetter.Status != entities.LetterOutgoingStatusDraft {
		return errors.New("only draft letters can be updated")
	}

	if letter.Subject == "" {
		return errors.New("letter subject cannot be empty")
	}

	return nil
}

func (p *LetterValidationProcessorImpl) ValidateDeleteOutgoingLetter(ctx context.Context, letter *entities.LetterOutgoing) error {
	if letter.Status != entities.LetterOutgoingStatusDraft {
		return errors.New("only draft letters can be deleted")
	}

	return nil
}

func (p *LetterValidationProcessorImpl) ValidateApprovalSubmission(ctx context.Context, letter *entities.LetterOutgoing) error {
	if letter.Status != entities.LetterOutgoingStatusDraft {
		return errors.New("only draft letters can be submitted for approval")
	}

	if letter.ApprovalFlowID == nil {
		return errors.New("approval flow is required for submission")
	}

	return nil
}