package appconfig

import (
	"fmt"
	"strconv"
	"strings"

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

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

func (h *Handler) GetGiftConfig(c *gin.Context) {
	item, err := h.service.GetGiftConfig(appctx.FromContext(c.Request.Context()))
	if err != nil {
		response.ServerError(c, "获取送礼配置失败")
		return
	}
	response.OK(c, item)
}

func (h *Handler) UpdateGiftConfig(c *gin.Context) {
	var request giftConfigRequest
	if err := c.ShouldBindJSON(&request); err != nil {
		response.BadRequest(c, "参数不正确")
		return
	}
	appCode := appctx.FromContext(c.Request.Context())
	item, err := h.service.UpdateGiftConfig(appCode, request)
	if err != nil {
		response.BadRequest(c, err.Error())
		return
	}
	// 审计记录最终规范化档位，避免仅有“保存成功”而无法还原当时对客户端下发的数量列表。
	parts := make([]string, 0, len(item.QuantityPresets))
	for _, value := range item.QuantityPresets {
		parts = append(parts, strconv.FormatInt(int64(value), 10))
	}
	shared.OperationLog(c, h.audit, "update-room-gift-config", "admin_app_configs", "success", fmt.Sprintf("app_code=%s quantity_presets=%s", item.AppCode, strings.Join(parts, ",")))
	response.OK(c, item)
}
