package tipos_servicos

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.TiposServico, error) {
	tipo, err := s.queries.CreateTipoServico(ctx, generated.CreateTipoServicoParams{
		Nome:   nome,
		Regiao: pgtype.Text{String: regiao, Valid: true},
	})
	if err != nil {
		return nil, err
	}
	return &tipo, nil
}

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

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

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

	tipo, err := s.queries.UpdateTipoServico(ctx, generated.UpdateTipoServicoParams{
		ID:     pgtype.UUID{Bytes: uuidVal, Valid: true},
		Nome:   nome,
		Regiao: pgtype.Text{String: regiao, Valid: true},
	})
	if err != nil {
		return nil, err
	}
	return &tipo, 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.DeleteTipoServico(ctx, generated.DeleteTipoServicoParams{
		ID:     pgtype.UUID{Bytes: uuidVal, Valid: true},
		Regiao: pgtype.Text{String: regiao, Valid: true},
	})
}
