package regionblock

import (
	"database/sql"
	"errors"
	"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 {
	service *Service
	audit   shared.OperationLogger
}

type replaceRequest struct {
	Keywords         *[]string `json:"keywords"`
	WhitelistIPs     *[]string `json:"whitelist_ips"`
	WhitelistUserIDs *[]string `json:"whitelist_user_ids"`
}

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

// ListRegionBlocks 返回用户管理 > 地区屏蔽页面需要的当前屏蔽词列表。
func (h *Handler) ListRegionBlocks(c *gin.Context) {
	items, err := h.service.List(c.Request.Context())
	if err != nil {
		response.ServerError(c, "获取地区屏蔽配置失败")
		return
	}
	response.OK(c, items)
}

// ReplaceRegionBlocks 保存整页地区屏蔽词配置；空数组表示清空屏蔽词。
func (h *Handler) ReplaceRegionBlocks(c *gin.Context) {
	var req replaceRequest
	if err := c.ShouldBindJSON(&req); err != nil || req.Keywords == nil {
		response.BadRequest(c, "地区屏蔽词参数不正确")
		return
	}
	items, err := h.service.Replace(c.Request.Context(), middleware.CurrentRequestID(c), int64(shared.ActorFromContext(c).UserID), *req.Keywords, req.WhitelistIPs, req.WhitelistUserIDs)
	if err != nil {
		if errors.Is(err, errInvalidPayload) {
			response.BadRequest(c, "地区屏蔽词参数不正确")
			return
		}
		if errors.Is(err, errWhitelistCacheRefresh) {
			response.ServerError(c, "保存成功但刷新登录风控缓存失败")
			return
		}
		response.ServerError(c, "保存地区屏蔽配置失败")
		return
	}
	shared.OperationLogWithResourceID(c, h.audit, "replace-region-blocks", "login_risk_country_blocks", middleware.CurrentRequestID(c), "success", fmt.Sprintf("keywords=%d whitelist_ips=%d whitelist_users=%d", len(items.Items), len(items.WhitelistItems), len(items.WhitelistUserItems)))
	response.OK(c, items)
}
