package userleaderboard

import (
	"database/sql"
	"errors"
	"strconv"
	"strings"

	"hyapp-admin-server/internal/appctx"
	"hyapp-admin-server/internal/integration/roomclient"
	"hyapp-admin-server/internal/modules/shared"
	"hyapp-admin-server/internal/response"

	"github.com/gin-gonic/gin"
)

type Handler struct {
	service *Service
}

func New(walletDB *sql.DB, userDB *sql.DB, room roomclient.Client) *Handler {
	return &Handler{service: NewService(walletDB, userDB, room)}
}

func (h *Handler) List(c *gin.Context) {
	query, ok := parseQuery(c)
	if !ok {
		return
	}

	result, err := h.service.List(c.Request.Context(), appctx.FromContext(c.Request.Context()), query)
	if err != nil {
		if errors.Is(err, errInvalidArgument) {
			response.BadRequest(c, "榜单参数不正确")
			return
		}
		response.ServerError(c, "获取用户榜单失败")
		return
	}
	response.OK(c, result)
}

func parseQuery(c *gin.Context) (Query, bool) {
	options := shared.ListOptions(c)
	boardType := NormalizeBoardType(firstQuery(c, "board_type", "boardType", "type"))
	if boardType == "" {
		response.BadRequest(c, "榜单类型不正确")
		return Query{}, false
	}

	period := NormalizePeriod(firstQuery(c, "period", "time_dimension", "timeDimension"))
	if period == "" {
		response.BadRequest(c, "时间维度不正确")
		return Query{}, false
	}

	viewerUserID, ok := optionalInt64(firstQuery(c, "viewer_user_id", "viewerUserId", "user_id", "userId"))
	if !ok {
		response.BadRequest(c, "用户 ID 不正确")
		return Query{}, false
	}

	return NormalizeQuery(Query{
		BoardType:    boardType,
		Period:       period,
		Page:         options.Page,
		PageSize:     options.PageSize,
		ViewerUserID: viewerUserID,
	}), true
}

func optionalInt64(raw string) (int64, bool) {
	raw = strings.TrimSpace(raw)
	if raw == "" {
		return 0, true
	}
	value, err := strconv.ParseInt(raw, 10, 64)
	return value, err == nil && value >= 0
}

func firstQuery(c *gin.Context, keys ...string) string {
	for _, key := range keys {
		if value := strings.TrimSpace(c.Query(key)); value != "" {
			return value
		}
	}
	return ""
}
