package funcoes

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.FuncoesProfissionai, error) {
	funcao, err := s.queries.CreateFuncao(ctx, nome)
	if err != nil {
		return nil, err
	}
	return &funcao, nil
}

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

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

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

	funcao, err := s.queries.UpdateFuncao(ctx, generated.UpdateFuncaoParams{
		ID:   pgtype.UUID{Bytes: uuidVal, Valid: true},
		Nome: nome,
	})
	if err != nil {
		return nil, err
	}
	return &funcao, 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.DeleteFuncao(ctx, pgtype.UUID{Bytes: uuidVal, Valid: true})
}
