package giftdiamond

import (
	"database/sql"
	"fmt"
	"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
	audit   shared.OperationLogger
}

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

func (h *Handler) List(c *gin.Context) {
	regionID, ok := optionalInt64Query(c, "region_id", "regionId")
	if !ok || regionID < 0 {
		response.BadRequest(c, "区域不正确")
		return
	}
	result, err := h.service.List(c.Request.Context(), appctx.FromContext(c.Request.Context()), regionID)
	if err != nil {
		response.ServerError(c, "获取礼物钻石比例失败")
		return
	}
	response.OK(c, result)
}

func optionalInt64Query(c *gin.Context, keys ...string) (int64, bool) {
	for _, key := range keys {
		value := strings.TrimSpace(c.Query(key))
		if value == "" {
			continue
		}
		parsed, err := strconv.ParseInt(value, 10, 64)
		if err != nil {
			return 0, false
		}
		return parsed, true
	}
	return 0, true
}

func (h *Handler) Update(c *gin.Context) {
	var req updateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "礼物钻石比例参数不正确")
		return
	}
	result, err := h.service.Update(c.Request.Context(), appctx.FromContext(c.Request.Context()), req, int64(shared.ActorFromContext(c).UserID))
	if err != nil {
		response.BadRequest(c, err.Error())
		return
	}
	shared.OperationLogWithResourceID(c, h.audit, "gift-diamond-ratio-update", "gift_diamond_ratio_configs", fmt.Sprintf("region:%d", result.RegionID), "success",
		fmt.Sprintf("region_id=%d ratios=%s", result.RegionID, strings.Join(ratioSummary(result.Items), ",")))
	response.OK(c, result)
}

func ratioSummary(items []ratioDTO) []string {
	result := make([]string, 0, len(items))
	for _, item := range items {
		result = append(result, item.GiftTypeCode+"="+item.RatioPercent+"/return="+item.ReturnCoinRatioPercent)
	}
	return result
}
