package anos_formaturas

import (
	"context"
	"errors"
	"regexp"

	"photum-backend/internal/db/generated"

	"github.com/google/uuid"
	"github.com/jackc/pgx/v5/pgtype"
)

type Service struct {
	queries *generated.Queries
}

func NewService(queries *generated.Queries) *Service {
	return &Service{queries: queries}
}

func (s *Service) Create(ctx context.Context, anoSemestre string, regiao string) (*generated.AnosFormatura, error) {
	// Validate format YYYY.S
	matched, _ := regexp.MatchString(`^\d{4}\.[1-2]$`, anoSemestre)
	if !matched {
		return nil, errors.New("invalid format. Expected YYYY.1 or YYYY.2")
	}

	ano, err := s.queries.CreateAnoFormatura(ctx, generated.CreateAnoFormaturaParams{
		AnoSemestre: anoSemestre,
		Regiao:      pgtype.Text{String: regiao, Valid: true},
	})
	if err != nil {
		return nil, err
	}
	return &ano, nil
}

func (s *Service) List(ctx context.Context, regiao string) ([]generated.AnosFormatura, error) {
	return s.queries.ListAnosFormaturas(ctx, pgtype.Text{String: regiao, Valid: true})
}

func (s *Service) GetByID(ctx context.Context, id string, regiao string) (*generated.AnosFormatura, error) {
	uuidVal, err := uuid.Parse(id)
	if err != nil {
		return nil, errors.New("invalid id")
	}
	ano, err := s.queries.GetAnoFormaturaByID(ctx, generated.GetAnoFormaturaByIDParams{
		ID:     pgtype.UUID{Bytes: uuidVal, Valid: true},
		Regiao: pgtype.Text{String: regiao, Valid: true},
	})
	if err != nil {
		return nil, err
	}
	return &ano, nil
}

func (s *Service) Update(ctx context.Context, id, anoSemestre string, regiao string) (*generated.AnosFormatura, error) {
	uuidVal, err := uuid.Parse(id)
	if err != nil {
		return nil, errors.New("invalid id")
	}

	// Validate format YYYY.S
	matched, _ := regexp.MatchString(`^\d{4}\.[1-2]$`, anoSemestre)
	if !matched {
		return nil, errors.New("invalid format. Expected YYYY.1 or YYYY.2")
	}

	ano, err := s.queries.UpdateAnoFormatura(ctx, generated.UpdateAnoFormaturaParams{
		ID:          pgtype.UUID{Bytes: uuidVal, Valid: true},
		AnoSemestre: anoSemestre,
		Regiao:      pgtype.Text{String: regiao, Valid: true},
	})
	if err != nil {
		return nil, err
	}
	return &ano, nil
}

func (s *Service) Delete(ctx context.Context, id string, regiao string) error {
	uuidVal, err := uuid.Parse(id)
	if err != nil {
		return errors.New("invalid id")
	}
	return s.queries.DeleteAnoFormatura(ctx, generated.DeleteAnoFormaturaParams{
		ID:     pgtype.UUID{Bytes: uuidVal, Valid: true},
		Regiao: pgtype.Text{String: regiao, Valid: true},
	})
}
