package giftrecord

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

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

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

type Handler struct {
	service *Service
}

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

func (h *Handler) List(c *gin.Context) {
	query, ok := parseListQuery(c)
	if !ok {
		return
	}
	items, total, err := h.service.List(c.Request.Context(), appctx.FromContext(c.Request.Context()), query)
	if err != nil {
		response.ServerError(c, "获取送礼记录失败")
		return
	}
	response.OK(c, response.Page{Items: items, Page: query.Page, PageSize: query.PageSize, Total: total})
}

func parseListQuery(c *gin.Context) (listQuery, bool) {
	options := shared.ListOptions(c)
	scene := strings.ToLower(strings.TrimSpace(firstQuery(c, "scene")))
	if scene == "all" {
		scene = ""
	}
	if scene != "" && scene != sceneRoom && scene != sceneDirect {
		response.BadRequest(c, "送礼场景不正确")
		return listQuery{}, false
	}
	startAtMS, ok := optionalInt64(c, "start_at_ms", "startAtMs")
	if !ok {
		response.BadRequest(c, "开始时间不正确")
		return listQuery{}, false
	}
	endAtMS, ok := optionalInt64(c, "end_at_ms", "endAtMs")
	if !ok {
		response.BadRequest(c, "结束时间不正确")
		return listQuery{}, false
	}
	if startAtMS > 0 && endAtMS > 0 && startAtMS >= endAtMS {
		response.BadRequest(c, "时间区间不正确")
		return listQuery{}, false
	}
	// 时间筛选统一为 [start_at_ms, end_at_ms)，与账务和统计边界保持一致，避免相邻区间重复展示同一笔送礼。
	return normalizeListQuery(listQuery{
		Page:         options.Page,
		PageSize:     options.PageSize,
		Scene:        scene,
		SenderFilter: shared.UserIdentityFilterFromQuery(c, "sender"),
		StartAtMS:    startAtMS,
		EndAtMS:      endAtMS,
	}), true
}

func optionalInt64(c *gin.Context, keys ...string) (int64, bool) {
	value := strings.TrimSpace(firstQuery(c, keys...))
	if value == "" {
		return 0, true
	}
	parsed, err := strconv.ParseInt(value, 10, 64)
	return parsed, err == nil && parsed >= 0
}

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