package processor

import (
	"context"
	"fmt"

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

// LetterNumberGenerator handles generation of letter numbers with configurable prefix and sequence
type LetterNumberGenerator interface {
	GenerateNumber(ctx context.Context, prefixKey, sequenceKey string, defaultPrefix string) (string, error)
}

type LetterNumberGeneratorImpl struct {
	settingRepo *repository.AppSettingRepository
}

func NewLetterNumberGenerator(settingRepo *repository.AppSettingRepository) *LetterNumberGeneratorImpl {
	return &LetterNumberGeneratorImpl{
		settingRepo: settingRepo,
	}
}

func (g *LetterNumberGeneratorImpl) GenerateNumber(ctx context.Context, prefixKey, sequenceKey string, defaultPrefix string) (string, error) {
	prefix := defaultPrefix
	if s, err := g.settingRepo.Get(ctx, prefixKey); err == nil {
		if v, ok := s.Value["value"].(string); ok && v != "" {
			prefix = v
		}
	}

	seq := 0
	if s, err := g.settingRepo.Get(ctx, sequenceKey); err == nil {
		if v, ok := s.Value["value"].(float64); ok {
			seq = int(v)
		}
	}

	seq = seq + 1

	letterNumber := fmt.Sprintf("%s%04d", prefix, seq)

	if err := g.settingRepo.Upsert(ctx, sequenceKey, entities.JSONB{"value": seq}); err != nil {
	}

	return letterNumber, nil
}

// GetCurrentSequence returns the current sequence number for a given key
func (g *LetterNumberGeneratorImpl) GetCurrentSequence(ctx context.Context, sequenceKey string) (int, error) {
	seq := 0
	if s, err := g.settingRepo.Get(ctx, sequenceKey); err == nil {
		if v, ok := s.Value["value"].(float64); ok {
			seq = int(v)
		}
	}
	return seq, nil
}

// GetPrefix returns the configured prefix for a given key
func (g *LetterNumberGeneratorImpl) GetPrefix(ctx context.Context, prefixKey string, defaultPrefix string) string {
	prefix := defaultPrefix
	if s, err := g.settingRepo.Get(ctx, prefixKey); err == nil {
		if v, ok := s.Value["value"].(string); ok && v != "" {
			prefix = v
		}
	}
	return prefix
}
