package regionblock

import (
	"database/sql"
	"errors"
	"fmt"

	"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"`
}

func New(userDB *sql.DB, audit shared.OperationLogger) *Handler {
	return &Handler{service: NewService(userDB), 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, gin.H{"items": items, "total": len(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(), int64(shared.ActorFromContext(c).UserID), *req.Keywords)
	if err != nil {
		if errors.Is(err, errInvalidPayload) {
			response.BadRequest(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", len(items)))
	response.OK(c, gin.H{"items": items, "total": len(items)})
}
