package handlers

import (
	"fmt"
	"strconv"

	"github.com/SamuelTariku/FortuneBet-Backend/internal/domain"
	"github.com/SamuelTariku/FortuneBet-Backend/internal/web_server/response"
	"github.com/gofiber/fiber/v2"
)

// GetAllLeagues godoc
// @Summary Gets all leagues
// @Description Gets all leagues
// @Tags leagues
// @Accept json
// @Produce json
// @Success 200 {array} domain.League
// @Failure 400 {object} response.APIResponse
// @Failure 500 {object} response.APIResponse
// @Router /leagues [get]
func (h *Handler) GetAllLeagues(c *fiber.Ctx) error {
	page := c.QueryInt("page", 1)
	pageSize := c.QueryInt("page_size", 10)

	limit := domain.ValidInt64{
		Value: int64(pageSize),
		Valid: pageSize == 0,
	}
	offset := domain.ValidInt64{
		Value: int64(page - 1),
		Valid: true,
	}

	countryCodeQuery := c.Query("cc")
	countryCode := domain.ValidString{
		Value: countryCodeQuery,
		Valid: countryCodeQuery != "",
	}
	isActiveQuery := c.QueryBool("is_active", false)
	isActiveFilter := c.QueryBool("is_active_filter", false)
	isActive := domain.ValidBool{
		Value: isActiveQuery,
		Valid: isActiveFilter,
	}

	sportIDQuery := c.Query("sport_id")
	var sportID domain.ValidInt32
	if sportIDQuery != "" {
		sportIDint, err := strconv.Atoi(sportIDQuery)
		if err != nil {
			h.logger.Error("invalid sport id", "error", err)
			return response.WriteJSON(c, fiber.StatusBadRequest, "invalid sport id", nil, nil)
		}
		sportID = domain.ValidInt32{
			Value: int32(sportIDint),
			Valid: true,
		}
	}

	leagues, err := h.leagueSvc.GetAllLeagues(c.Context(), domain.LeagueFilter{
		CountryCode: countryCode,
		IsActive:    isActive,
		SportID:     sportID,
		Limit:       limit,
		Offset:      offset,
	})

	if err != nil {
		fmt.Printf("Error fetching league %v \n", err)
		h.logger.Error("Failed to get leagues", "error", err)
		return response.WriteJSON(c, fiber.StatusInternalServerError, "Failed to get leagues", err, nil)
	}
	return response.WriteJSON(c, fiber.StatusOK, "All leagues retrieved", leagues, nil)
}

type SetLeagueActiveReq struct {
	IsActive bool `json:"is_active"`
}

func (h *Handler) SetLeagueActive(c *fiber.Ctx) error {
	fmt.Printf("Set Active Leagues")
	leagueIdStr := c.Params("id")
	if leagueIdStr == "" {
		response.WriteJSON(c, fiber.StatusBadRequest, "Missing league id", nil, nil)
	}
	leagueId, err := strconv.Atoi(leagueIdStr)
	if err != nil {
		response.WriteJSON(c, fiber.StatusBadRequest, "invalid league id", nil, nil)
	}

	var req SetLeagueActiveReq
	if err := c.BodyParser(&req); err != nil {
		h.logger.Error("SetLeagueReq failed", "error", err)
		return response.WriteJSON(c, fiber.StatusBadRequest, "Failed to parse request", err, nil)
	}

	valErrs, ok := h.validator.Validate(c, req)
	if !ok {
		return response.WriteJSON(c, fiber.StatusBadRequest, "Invalid request", valErrs, nil)
	}

	if err := h.leagueSvc.SetLeagueActive(c.Context(), int64(leagueId), req.IsActive); err != nil {
		response.WriteJSON(c, fiber.StatusInternalServerError, "Failed to update league", err, nil)
	}

	return response.WriteJSON(c, fiber.StatusOK, "League updated successfully", nil, nil)
}
