package empresas

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

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

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

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

	empresa, err := s.queries.UpdateEmpresa(ctx, generated.UpdateEmpresaParams{
		ID:     pgtype.UUID{Bytes: uuidVal, Valid: true},
		Nome:   nome,
		Regiao: pgtype.Text{String: regiao, Valid: true},
	})
	if err != nil {
		return nil, err
	}
	return &empresa, 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.DeleteEmpresa(ctx, generated.DeleteEmpresaParams{
		ID:     pgtype.UUID{Bytes: uuidVal, Valid: true},
		Regiao: pgtype.Text{String: regiao, Valid: true},
	})
}
