package pointwithdrawalconfig

import (
	"database/sql"
	"errors"
	"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, userDB *sql.DB, audit shared.OperationLogger) *Handler {
	return &Handler{service: NewService(walletDB, userDB), audit: audit}
}

func (h *Handler) List(c *gin.Context) {
	items, err := h.service.List(c.Request.Context(), appctx.FromContext(c.Request.Context()))
	if err != nil {
		response.ServerError(c, "获取币商提现白名单失败")
		return
	}
	response.OK(c, map[string]any{"items": items})
}

func (h *Handler) Upsert(c *gin.Context) {
	var req upsertRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "币商提现配置参数不正确")
		return
	}
	item, err := h.service.Upsert(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, "point-withdrawal-coin-seller-upsert", "point_withdrawal_coin_seller_configs", item.AppCode+":"+item.SellerUserID, "success", "ratio="+strconv.FormatInt(item.PointAmount, 10)+":"+strconv.FormatInt(item.SellerCoinAmount, 10))
	response.OK(c, item)
}

func (h *Handler) Delete(c *gin.Context) {
	sellerUserID, err := strconv.ParseInt(strings.TrimSpace(c.Param("seller_user_id")), 10, 64)
	if err != nil || sellerUserID <= 0 {
		response.BadRequest(c, "币商 ID 不正确")
		return
	}
	appCode := appctx.FromContext(c.Request.Context())
	if err := h.service.Delete(c.Request.Context(), appCode, sellerUserID); err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			response.NotFound(c, "配置不存在")
			return
		}
		response.ServerError(c, "删除币商提现配置失败")
		return
	}
	shared.OperationLogWithResourceID(c, h.audit, "point-withdrawal-coin-seller-delete", "point_withdrawal_coin_seller_configs", appCode+":"+strconv.FormatInt(sellerUserID, 10), "success", "")
	response.OK(c, map[string]any{"deleted": true})
}
