package minesweeper

import (
	"bindbox-game/internal/pkg/core"
	"bindbox-game/internal/repository/mysql"

	"go.uber.org/zap"
)

type Handler struct {
	logger *zap.Logger
	db     mysql.Repo
}

func New(logger *zap.Logger, db mysql.Repo) *Handler {
	return &Handler{
		logger: logger,
		db:     db,
	}
}

// i() 辅助函数
func (h *Handler) i() {}

// VerifyTicket 验证游戏票据
// @Summary 验证游戏票据
// @Description 验证游戏票据是否有效
// @Tags Internal
// @Accept json
// @Produce json
// @Param ticket body VerifyTicketRequest true "票据信息"
// @Success 200 {object} VerifyTicketResponse
// @Router /internal/game/verify [post]
func (h *Handler) VerifyTicket() core.HandlerFunc {
	return func(c core.Context) {
		req := new(VerifyTicketRequest)
		if err := c.ShouldBindJSON(req); err != nil {
			c.AbortWithError(core.Error(
				400,
				10001,
				"参数错误",
			))
			return
		}

		// TODO: 实际验证逻辑，这里先Mock通过
		// 实际应该检查Redis中ticket是否存在且对应正确的user_id

		c.Payload(VerifyTicketResponse{
			Valid:          true,
			UserID:         req.UserID,
			RemainingTimes: 1, // Mock
		})
	}
}

// SettleGame 结算游戏
// @Summary 结算游戏
// @Description 游戏结束后结算并发放奖励
// @Tags Internal
// @Accept json
// @Produce json
// @Param result body SettleGameRequest true "结算信息"
// @Success 200 {object} SettleGameResponse
// @Router /internal/game/settle [post]
func (h *Handler) SettleGame() core.HandlerFunc {
	return func(c core.Context) {
		req := new(SettleGameRequest)
		if err := c.ShouldBindJSON(req); err != nil {
			c.AbortWithError(core.Error(
				400,
				10001,
				"参数错误",
			))
			return
		}

		// TODO: 实际结算逻辑
		// 1. 验证 ticket 状态为“进行中”
		// 2. 如果 Win=true，发放奖励
		// 3. 标记 ticket 为“已完成”

		h.logger.Info("Game Settled", 
			zap.String("user_id", req.UserID), 
			zap.Bool("win", req.Win),
			zap.Int("score", req.Score),
		)

		c.Payload(SettleGameResponse{
			Success: true,
			Reward:  "100积分", // Mock
		})
	}
}

type VerifyTicketRequest struct {
	UserID string `json:"user_id"`
	Ticket string `json:"ticket"`
}

type VerifyTicketResponse struct {
	Valid          bool   `json:"valid"`
	UserID         string `json:"user_id"`
	RemainingTimes int    `json:"remaining_times"`
}

type SettleGameRequest struct {
	UserID   string `json:"user_id"`
	Ticket   string `json:"ticket"`
	MatchID  string `json:"match_id"`
	Win      bool   `json:"win"`
	Score    int    `json:"score"`
	Metadata string `json:"metadata"`
}

type SettleGameResponse struct {
	Success bool   `json:"success"`
	Reward  string `json:"reward"`
}
