package riskconfig

import (
	"fmt"

	"hyapp-admin-server/internal/integration/userclient"
	"hyapp-admin-server/internal/middleware"
	"hyapp-admin-server/internal/modules/shared"
	"hyapp-admin-server/internal/response"

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

type Handler struct {
	user  userclient.Client
	audit shared.OperationLogger
}

func New(user userclient.Client, audit shared.OperationLogger) *Handler {
	return &Handler{user: user, audit: audit}
}

type registerRiskConfigRequest struct {
	MaxAccountsPerDevice int32 `json:"max_accounts_per_device"`
}

func (h *Handler) GetRegisterRiskConfig(c *gin.Context) {
	config, err := h.user.GetRegisterRiskConfig(c.Request.Context(), userclient.GetRegisterRiskConfigRequest{
		RequestID: middleware.CurrentRequestID(c),
		Caller:    "admin-server",
	})
	if err != nil {
		response.ServerError(c, "获取风控配置失败")
		return
	}
	response.OK(c, config)
}

func (h *Handler) UpdateRegisterRiskConfig(c *gin.Context) {
	var req registerRiskConfigRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "风控配置参数不正确")
		return
	}
	if req.MaxAccountsPerDevice < 1 {
		response.BadRequest(c, "单设备最大账号数必须大于 0")
		return
	}
	config, err := h.user.UpdateRegisterRiskConfig(c.Request.Context(), userclient.UpdateRegisterRiskConfigRequest{
		RequestID:            middleware.CurrentRequestID(c),
		Caller:               "admin-server",
		MaxAccountsPerDevice: req.MaxAccountsPerDevice,
		OperatorAdminID:      int64(middleware.CurrentUserID(c)),
	})
	if err != nil {
		response.BadRequest(c, err.Error())
		return
	}
	shared.OperationLog(c, h.audit, "update-risk-config", "auth_risk_configs", "success", fmt.Sprintf("max_accounts_per_device=%d", config.MaxAccountsPerDevice))
	response.OK(c, config)
}
