package handlers

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

// LaunchAleaGame godoc
// @Summary Launch an Alea Play virtual game
// @Description Generates an authenticated launch URL for Alea Play virtual games
// @Tags Alea Virtual Games
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param game_id query string true "Game identifier (e.g., 'aviator', 'plinko')"
// @Param currency query string false "Currency code (ISO 4217)" Enums(USD, EUR, GBP) default(USD)
// @Param mode query string false "Game mode" Enums(real, demo) default(real)
// @Success 200 {object} map[string]string{launch_url=string} "Returns authenticated game launch URL"
// @Router /api/v1/alea-games/launch [get]
func (h *Handler) LaunchAleaGame(c *fiber.Ctx) error {
	userID := c.Locals("user_id").(int64)
	gameID := c.Query("game_id")
	currency := c.Query("currency", "USD")
	mode := c.Query("mode", "real") // real or demo

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

	return c.JSON(fiber.Map{
		"launch_url": launchURL,
		"message":    "Game launched successfully",
	})
}

// HandleAleaCallback godoc
// @Summary Process Alea Play game callback
// @Description Handles webhook callbacks from Alea Play virtual games for bet settlement
// @Tags Alea Virtual Games
// @Accept json
// @Produce json
// @Param callback body domain.AleaPlayCallback true "Callback payload"
// @Success 200 {object} map[string]string{status=string} "Callback processed successfully"
// @Router /api/v1/webhooks/alea [post]
func (h *Handler) HandleAleaCallback(c *fiber.Ctx) error {
	var cb domain.AleaPlayCallback
	if err := c.BodyParser(&cb); err != nil {
		h.logger.Error("invalid Alea callback format", "error", err)
		return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
			"error": "invalid callback format",
		})
	}

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

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