package teamsalarypolicy

import (
	"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, audit shared.OperationLogger) *Handler {
	return &Handler{service: NewService(store), audit: audit}
}

func (h *Handler) ListPolicies(c *gin.Context) {
	options := shared.ListOptions(c)
	policyType := firstQuery(c, "policy_type", "policyType")
	items, total, err := h.service.List(appctx.FromContext(c.Request.Context()), repository.TeamSalaryPolicyListOptions{
		PolicyType:            policyType,
		Keyword:               options.Keyword,
		RegionID:              queryInt64(c, "region_id", "regionId"),
		Status:                options.Status,
		SettlementTriggerMode: firstQuery(c, "settlement_trigger_mode", "settlementTriggerMode"),
		Page:                  options.Page,
		PageSize:              options.PageSize,
	})
	if err != nil {
		response.BadRequest(c, err.Error())
		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-team-salary-policy", "admin_team_salary_policies", strconv.FormatUint(uint64(item.ID), 10), "success", fmt.Sprintf("policy_type=%s region_id=%d", item.PolicyType, item.RegionID))
	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
	}
	item, err := h.service.Update(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-team-salary-policy", "admin_team_salary_policies", strconv.FormatUint(uint64(item.ID), 10), "success", fmt.Sprintf("policy_type=%s region_id=%d", item.PolicyType, item.RegionID))
	response.OK(c, item)
}

func (h *Handler) DeletePolicy(c *gin.Context) {
	id, ok := policyID(c)
	if !ok {
		return
	}
	policyType := firstQuery(c, "policy_type", "policyType")
	if err := h.service.Delete(appctx.FromContext(c.Request.Context()), policyType, id); err != nil {
		response.BadRequest(c, err.Error())
		return
	}
	shared.OperationLogWithResourceID(c, h.audit, "delete-team-salary-policy", "admin_team_salary_policies", strconv.FormatUint(uint64(id), 10), "success", fmt.Sprintf("policy_type=%s", normalizePolicyType(policyType)))
	response.OK(c, gin.H{"deleted": true})
}

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