package availability

import (
	"context"
	"time"

	"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}
}

type SetAvailabilityInput struct {
	Date   string `json:"date"`   // YYYY-MM-DD
	Status string `json:"status"` // DISPONIVEL, INDISPONIVEL
}

func (s *Service) SetAvailability(ctx context.Context, userID string, input SetAvailabilityInput) error {
	userUUID, err := uuid.Parse(userID)
	if err != nil {
		return err
	}

	date, err := time.Parse("2006-01-02", input.Date)
	if err != nil {
		return err
	}

	pgDate := pgtype.Date{Time: date, Valid: true}

	if input.Status == "INDISPONIVEL" {
		// Remove record if unavailable (or explicit status if we prefer history, but opt-in usually means record exists = available)
		// Specifically for this implementation, let's follow the schema which has a status column.
		// However, "availability" usually implies "I am available".
		// If I set "INDISPONIVEL", I can either delete the record or set status to INDISPONIVEL.
		// Let's set status.
	}

	_, err = s.queries.CreateDisponibilidade(ctx, generated.CreateDisponibilidadeParams{
		UsuarioID: pgtype.UUID{Bytes: userUUID, Valid: true},
		Data:      pgDate,
		Status:    input.Status,
	})
	return err
}

func (s *Service) ListMyAvailability(ctx context.Context, userID string, startDate, endDate string) ([]generated.DisponibilidadeProfissionai, error) {
	userUUID, err := uuid.Parse(userID)
	if err != nil {
		return nil, err
	}

	start, err := time.Parse("2006-01-02", startDate)
	if err != nil {
		return nil, err
	}
	end, err := time.Parse("2006-01-02", endDate)
	if err != nil {
		return nil, err
	}

	return s.queries.ListDisponibilidadeByPeriod(ctx, generated.ListDisponibilidadeByPeriodParams{
		UsuarioID: pgtype.UUID{Bytes: userUUID, Valid: true},
		Data:      pgtype.Date{Time: start, Valid: true},
		Data_2:    pgtype.Date{Time: end, Valid: true},
	})
}
