package handlers

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

func (h *Handler) CreateReferralCode(c *fiber.Ctx) error {
	userID, ok := c.Locals("user_id").(int64)
	if !ok || userID == 0 {
		h.logger.Error("Invalid user ID in context")
		return fiber.NewError(fiber.StatusUnauthorized, "Invalid user identification")
	}

	if err := h.referralSvc.CreateReferral(c.Context(), userID); err != nil {
		h.logger.Error("Failed to create referral", "userID", userID, "error", err)
		return fiber.NewError(fiber.StatusInternalServerError, "Failed to create referral")
	}

	return response.WriteJSON(c, fiber.StatusOK, "Referral created successfully", nil, nil)
}

// GetReferralStats godoc
// @Summary Get referral statistics
// @Description Retrieves referral statistics for the authenticated user
// @Tags referral
// @Accept json
// @Produce json
// @Success 200 {object} domain.ReferralStats
// @Failure 401 {object} response.APIResponse
// @Failure 500 {object} response.APIResponse
// @Security Bearer
// @Router /referral/stats [get]
func (h *Handler) GetReferralStats(c *fiber.Ctx) error {
	userID, ok := c.Locals("user_id").(int64)
	if !ok || userID == 0 {
		h.logger.Error("Invalid user ID in context")
		return fiber.NewError(fiber.StatusUnauthorized, "Invalid user identification")
	}

	user, err := h.userSvc.GetUserByID(c.Context(), userID)
	if err != nil {
		h.logger.Error("Failed to get user", "userID", userID, "error", err)
		return fiber.NewError(fiber.StatusInternalServerError, "Failed to retrieve user")
	}

	stats, err := h.referralSvc.GetReferralStats(c.Context(), user.PhoneNumber)
	if err != nil {
		h.logger.Error("Failed to get referral stats", "userID", userID, "error", err)
		return fiber.NewError(fiber.StatusInternalServerError, "Failed to retrieve referral stats")
	}

	return response.WriteJSON(c, fiber.StatusOK, "Referral stats retrieved successfully", stats, nil)
}

// UpdateReferralSettings godoc
// @Summary Update referral settings
// @Description Updates referral settings (admin only)
// @Tags referral
// @Accept json
// @Produce json
// @Param settings body domain.ReferralSettings true "Referral settings"
// @Success 200 {object} response.APIResponse
// @Failure 401 {object} response.APIResponse
// @Failure 403 {object} response.APIResponse
// @Failure 500 {object} response.APIResponse
// @Security Bearer
// @Router /referral/settings [put]
func (h *Handler) UpdateReferralSettings(c *fiber.Ctx) error {
	userID, ok := c.Locals("user_id").(int64)
	if !ok || userID == 0 {
		h.logger.Error("Invalid user ID in context")
		return fiber.NewError(fiber.StatusUnauthorized, "Invalid user identification")
	}

	user, err := h.userSvc.GetUserByID(c.Context(), userID)
	if err != nil {
		h.logger.Error("Failed to get user", "userID", userID, "error", err)
		return fiber.NewError(fiber.StatusInternalServerError, "Failed to retrieve user")
	}

	if user.Role != domain.RoleAdmin {
		return fiber.NewError(fiber.StatusForbidden, "Admin access required")
	}

	var settings domain.ReferralSettings
	if err := c.BodyParser(&settings); err != nil {
		h.logger.Error("Failed to parse settings", "error", err)
		return fiber.NewError(fiber.StatusBadRequest, "Invalid request body")
	}

	settings.UpdatedBy = user.PhoneNumber
	if err := h.referralSvc.UpdateReferralSettings(c.Context(), &settings); err != nil {
		h.logger.Error("Failed to update referral settings", "error", err)
		return fiber.NewError(fiber.StatusInternalServerError, "Failed to update referral settings")
	}

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

// GetReferralSettings godoc
// @Summary Get referral settings
// @Description Retrieves current referral settings (admin only)
// @Tags referral
// @Accept json
// @Produce json
// @Success 200 {object} domain.ReferralSettings
// @Failure 401 {object} response.APIResponse
// @Failure 403 {object} response.APIResponse
// @Failure 500 {object} response.APIResponse
// @Security Bearer
// @Router /referral/settings [get]
func (h *Handler) GetReferralSettings(c *fiber.Ctx) error {
	userID, ok := c.Locals("user_id").(int64)
	if !ok || userID == 0 {
		h.logger.Error("Invalid user ID in context")
		return fiber.NewError(fiber.StatusUnauthorized, "Invalid user identification")
	}

	user, err := h.userSvc.GetUserByID(c.Context(), userID)
	if err != nil {
		h.logger.Error("Failed to get user", "userID", userID, "error", err)
		return fiber.NewError(fiber.StatusInternalServerError, "Failed to retrieve user")
	}

	if user.Role != domain.RoleAdmin {
		return fiber.NewError(fiber.StatusForbidden, "Admin access required")
	}

	settings, err := h.referralSvc.GetReferralSettings(c.Context())
	if err != nil {
		h.logger.Error("Failed to get referral settings", "error", err)
		return fiber.NewError(fiber.StatusInternalServerError, "Failed to retrieve referral settings")
	}

	return response.WriteJSON(c, fiber.StatusOK, "Referral settings retrieved successfully", settings, nil)
}
