package handlers

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

// LaunchVeliGame godoc
// @Summary Launch a Veli game
// @Description Generates authenticated launch URL for Veli games
// @Tags Veli Games
// @Security BearerAuth
// @Param game_id path string true "Game ID (e.g., veli_aviator_v1)"
// @Param currency query string false "Currency code" default(USD)
// @Param mode query string false "Game mode" Enums(real, demo) default(real)
// @Success 200 {object} map[string]string "Returns launch URL"
// @Failure 400 {object} map[string]string "Invalid request"
// @Failure 500 {object} map[string]string "Internal server error"
// @Router /api/veli/launch/{game_id} [get]
func (h *Handler) LaunchVeliGame(c *fiber.Ctx) error {
	userID := c.Locals("userID").(int64)
	gameID := c.Params("game_id")
	currency := c.Query("currency", "USD")
	mode := c.Query("mode", "real")

	launchURL, err := h.veliVirtualGameSvc.GenerateGameLaunchURL(c.Context(), userID, gameID, currency, mode)
	if err != nil {
		h.logger.Error("failed to generate Veli launch URL",
			"error", err,
			"userID", userID,
			"gameID", gameID)
		return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
			"error": "failed to launch game",
		})
	}

	return c.JSON(fiber.Map{
		"launch_url": launchURL,
	})
}

// HandleVeliCallback godoc
// @Summary Veli Games webhook handler
// @Description Processes game round settlements from Veli
// @Tags Veli Games
// @Accept json
// @Produce json
// @Param payload body domain.VeliCallback true "Callback payload"
// @Success 200 {object} map[string]string "Callback processed"
// @Failure 400 {object} map[string]string "Invalid payload"
// @Failure 403 {object} map[string]string "Invalid signature"
// @Failure 500 {object} map[string]string "Processing error"
// @Router /webhooks/veli [post]
func (h *Handler) HandleVeliCallback(c *fiber.Ctx) error {
	var cb domain.VeliCallback
	if err := c.BodyParser(&cb); err != nil {
		h.logger.Error("invalid Veli callback format", "error", err)
		return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
			"error": "invalid payload format",
		})
	}

	if err := h.veliVirtualGameSvc.HandleCallback(c.Context(), &cb); err != nil {
		h.logger.Error("failed to process Veli callback",
			"roundID", cb.RoundID,
			"error", err)
		return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
			"error": "failed to process callback",
		})
	}

	return c.JSON(fiber.Map{
		"status": "processed",
	})
}
