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) (*generated.TiposServico, error) {
	tipo, err := s.queries.CreateTipoServico(ctx, nome)
	if err != nil {
		return nil, err
	}
	return &tipo, nil
}

func (s *Service) List(ctx context.Context) ([]generated.TiposServico, error) {
	return s.queries.ListTiposServicos(ctx)
}

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

func (s *Service) Update(ctx context.Context, id, nome 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,
	})
	if err != nil {
		return nil, err
	}
	return &tipo, nil
}

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