package cursos

import (
	"context"
	"errors"

	"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, nome string, regiao string) (*generated.Curso, error) {
	curso, err := s.queries.CreateCurso(ctx, generated.CreateCursoParams{
		Nome:   nome,
		Regiao: pgtype.Text{String: regiao, Valid: true},
	})
	if err != nil {
		return nil, err
	}
	return &curso, nil
}

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

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

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

	curso, err := s.queries.UpdateCurso(ctx, generated.UpdateCursoParams{
		ID:     pgtype.UUID{Bytes: uuidVal, Valid: true},
		Nome:   nome,
		Regiao: pgtype.Text{String: regiao, Valid: true},
	})
	if err != nil {
		return nil, err
	}
	return &curso, 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.DeleteCurso(ctx, generated.DeleteCursoParams{
		ID:     pgtype.UUID{Bytes: uuidVal, Valid: true},
		Regiao: pgtype.Text{String: regiao, Valid: true},
	})
}
