package hostagencypolicy

import (
	"database/sql"
	"fmt"
	"strconv"
	"strings"

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

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

type Handler struct {
	service *Service
	audit   shared.OperationLogger
}

func New(store *repository.Store, walletDB *sql.DB, audit shared.OperationLogger) *Handler {
	return &Handler{service: NewService(store, walletDB), audit: audit}
}

func (h *Handler) ListPolicies(c *gin.Context) {
	options := shared.ListOptions(c)
	cycleKey := firstQuery(c, "cycle_key", "cycleKey")
	if cycleKey != "" {
		if _, err := normalizePolicyCycleKey(cycleKey); err != nil {
			response.BadRequest(c, err.Error())
			return
		}
	}
	// query 层保留 snake_case/camelCase 两种写法，兼容生成端和手写端调用。
	items, total, err := h.service.List(c.Request.Context(), appctx.FromContext(c.Request.Context()), repository.HostAgencySalaryPolicyListOptions{
		Keyword:        options.Keyword,
		PolicyType:     firstQuery(c, "policy_type", "policyType"),
		RegionID:       queryInt64(c, "region_id", "regionId"),
		CycleKey:       cycleKey,
		Status:         options.Status,
		SettlementMode: firstQuery(c, "settlement_mode", "settlementMode"),
		// trigger mode 可直接筛出“只允许手动结算”的政策，后续工资结算页会复用同一查询口径。
		SettlementTriggerMode: firstQuery(c, "settlement_trigger_mode", "settlementTriggerMode"),
		Page:                  options.Page,
		PageSize:              options.PageSize,
	})
	if err != nil {
		response.ServerError(c, "获取工资政策配置失败")
		return
	}
	response.OK(c, response.Page{Items: items, Page: options.Page, PageSize: options.PageSize, Total: total})
}

func (h *Handler) CreatePolicy(c *gin.Context) {
	var req policyRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "工资政策参数不正确")
		return
	}
	// 操作人只从登录上下文取，不信任请求体，方便后续审计定位配置变更来源。
	item, err := h.service.Create(appctx.FromContext(c.Request.Context()), shared.ActorFromContext(c).UserID, req)
	if err != nil {
		response.BadRequest(c, err.Error())
		return
	}
	shared.OperationLogWithResourceID(c, h.audit, "create-host-agency-policy", "admin_host_agency_salary_policies", strconv.FormatUint(uint64(item.ID), 10), "success", fmt.Sprintf("region_ids=%v", item.RegionIDs))
	response.Created(c, item)
}

func (h *Handler) UpdatePolicy(c *gin.Context) {
	id, ok := policyID(c)
	if !ok {
		return
	}
	var req policyRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "工资政策参数不正确")
		return
	}
	// PUT 语义是整条政策配置替换，等级明细也会由 service/repository 按整包替换。
	item, err := h.service.Update(c.Request.Context(), appctx.FromContext(c.Request.Context()), shared.ActorFromContext(c).UserID, id, req)
	if err != nil {
		response.BadRequest(c, err.Error())
		return
	}
	shared.OperationLogWithResourceID(c, h.audit, "update-host-agency-policy", "admin_host_agency_salary_policies", strconv.FormatUint(uint64(item.ID), 10), "success", fmt.Sprintf("region_ids=%v", item.RegionIDs))
	response.OK(c, item)
}

func (h *Handler) DeletePolicy(c *gin.Context) {
	id, ok := policyID(c)
	if !ok {
		return
	}
	if err := h.service.Delete(c.Request.Context(), appctx.FromContext(c.Request.Context()), id); err != nil {
		response.BadRequest(c, err.Error())
		return
	}
	shared.OperationLogWithResourceID(c, h.audit, "delete-host-agency-policy", "admin_host_agency_salary_policies", strconv.FormatUint(uint64(id), 10), "success", "")
	response.OK(c, gin.H{"deleted": true})
}

func (h *Handler) PublishPolicy(c *gin.Context) {
	id, ok := policyID(c)
	if !ok {
		return
	}
	item, err := h.service.Publish(c.Request.Context(), appctx.FromContext(c.Request.Context()), shared.ActorFromContext(c).UserID, id)
	if err != nil {
		response.BadRequest(c, err.Error())
		return
	}
	shared.OperationLogWithResourceID(c, h.audit, "publish-host-agency-policy", "admin_host_agency_salary_policies", strconv.FormatUint(uint64(item.ID), 10), "success", fmt.Sprintf("region_ids=%v status=%s", item.RegionIDs, item.Status))
	response.OK(c, item)
}

func policyID(c *gin.Context) (uint, bool) {
	value := strings.TrimSpace(c.Param("policy_id"))
	parsed, err := strconv.ParseUint(value, 10, 64)
	if err != nil || parsed == 0 {
		response.BadRequest(c, "工资政策 ID 不正确")
		return 0, false
	}
	return uint(parsed), true
}

func queryInt64(c *gin.Context, keys ...string) int64 {
	value := strings.TrimSpace(firstQuery(c, keys...))
	if value == "" {
		return 0
	}
	parsed, err := strconv.ParseInt(value, 10, 64)
	if err != nil || parsed < 0 {
		return 0
	}
	return parsed
}

func firstQuery(c *gin.Context, keys ...string) string {
	for _, key := range keys {
		if value := strings.TrimSpace(c.Query(key)); value != "" {
			return value
		}
	}
	return ""
}
