package hostsalarysettlement

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

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

	walletv1 "hyapp.local/api/proto/wallet/v1"

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

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

func New(walletDB *sql.DB, userDB *sql.DB, walletCron walletv1.WalletCronServiceClient, requestTimeout time.Duration, audit shared.OperationLogger) *Handler {
	return &Handler{audit: audit, service: NewService(walletDB, userDB, walletCron, requestTimeout)}
}

func (h *Handler) ListPending(c *gin.Context) {
	req, ok := parsePendingQuery(c)
	if !ok {
		return
	}
	items, total, err := h.service.ListPending(c.Request.Context(), appctx.FromContext(c.Request.Context()), req)
	if err != nil {
		response.ServerError(c, "获取 Host/Agency 待结算工资失败")
		return
	}
	response.OK(c, response.Page{Items: items, Page: req.Page, PageSize: req.PageSize, Total: total})
}

func (h *Handler) List(c *gin.Context) {
	req, ok := parseQuery(c)
	if !ok {
		return
	}
	items, total, err := h.service.List(c.Request.Context(), appctx.FromContext(c.Request.Context()), req)
	if err != nil {
		response.ServerError(c, "获取工资结算记录失败")
		return
	}
	response.OK(c, response.Page{Items: items, Page: req.Page, PageSize: req.PageSize, Total: total})
}

func (h *Handler) Settle(c *gin.Context) {
	var req settleRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "结算参数不正确")
		return
	}
	rawSettlementType := strings.TrimSpace(req.SettlementType)
	rawTriggerMode := strings.TrimSpace(req.TriggerMode)
	rawRole := strings.TrimSpace(req.Role)
	req = normalizeSettleRequest(req)
	if rawRole != "" && normalizeSettlementRole(rawRole) == "" {
		response.BadRequest(c, "结算角色不正确")
		return
	}
	if rawSettlementType != "" && normalizeSettlementType(rawSettlementType) == "" {
		response.BadRequest(c, "结算类型不正确")
		return
	}
	if rawTriggerMode != "" && normalizeTriggerMode(rawTriggerMode) == "" {
		response.BadRequest(c, "触发方式不正确")
		return
	}
	result, err := h.service.Settle(c.Request.Context(), appctx.FromContext(c.Request.Context()), int64(shared.ActorFromContext(c).UserID), req)
	if err != nil {
		response.ServerError(c, "Host/Agency 工资结算失败")
		return
	}
	shared.OperationLog(c, h.audit, "settle-host-salary", "host_salary_settlement_records", "success", fmt.Sprintf("role=%s settlement_type=%s trigger_mode=%s cycle_key=%s success=%d skipped=%d failed=%d", result.Role, result.SettlementType, result.TriggerMode, result.CycleKey, result.SuccessCount, result.SkippedCount, result.FailureCount))
	response.OK(c, result)
}

func parseQuery(c *gin.Context) (query, bool) {
	options := shared.ListOptions(c)
	userID, ok := optionalInt64(c, "user_id", "userId")
	if !ok {
		response.BadRequest(c, "主播用户 ID 不正确")
		return query{}, false
	}
	agencyOwnerUserID, ok := optionalInt64(c, "agency_owner_user_id", "agencyOwnerUserId")
	if !ok {
		response.BadRequest(c, "代理用户 ID 不正确")
		return query{}, false
	}
	policyID, ok := optionalUint64(c, "policy_id", "policyId")
	if !ok {
		response.BadRequest(c, "政策 ID 不正确")
		return query{}, false
	}
	startAtMS, ok := optionalInt64(c, "start_at_ms", "startAtMs")
	if !ok {
		response.BadRequest(c, "开始时间不正确")
		return query{}, false
	}
	endAtMS, ok := optionalInt64(c, "end_at_ms", "endAtMs")
	if !ok {
		response.BadRequest(c, "结束时间不正确")
		return query{}, false
	}
	if startAtMS > 0 && endAtMS > 0 && startAtMS >= endAtMS {
		response.BadRequest(c, "时间区间不正确")
		return query{}, false
	}
	req := normalizeQuery(query{
		Page:              options.Page,
		PageSize:          options.PageSize,
		CycleKey:          strings.TrimSpace(firstQuery(c, "cycle_key", "cycleKey")),
		SettlementType:    normalizeSettlementType(firstQuery(c, "settlement_type", "settlementType")),
		Status:            normalizeStatus(firstQuery(c, "status")),
		UserID:            userID,
		UserFilter:        shared.UserIdentityFilterFromQuery(c, ""),
		AgencyOwnerUserID: agencyOwnerUserID,
		AgencyOwnerFilter: shared.UserIdentityFilterFromQuery(c, "agency_owner"),
		PolicyID:          policyID,
		StartAtMS:         startAtMS,
		EndAtMS:           endAtMS,
	})
	if rawType := strings.TrimSpace(firstQuery(c, "settlement_type", "settlementType")); rawType != "" && strings.ToLower(rawType) != "all" && req.SettlementType == "" {
		response.BadRequest(c, "结算类型不正确")
		return query{}, false
	}
	if rawStatus := strings.TrimSpace(firstQuery(c, "status")); rawStatus != "" && strings.ToLower(rawStatus) != "all" && req.Status == "" {
		response.BadRequest(c, "结算状态不正确")
		return query{}, false
	}
	return req, true
}

func parsePendingQuery(c *gin.Context) (pendingQuery, bool) {
	options := shared.ListOptions(c)
	req := pendingQuery{
		Page:           options.Page,
		PageSize:       options.PageSize,
		Role:           normalizeSettlementRole(firstQuery(c, "role", "settlement_role", "settlementRole")),
		CycleKey:       strings.TrimSpace(firstQuery(c, "cycle_key", "cycleKey")),
		SettlementType: normalizeSettlementType(firstQuery(c, "settlement_type", "settlementType")),
		TriggerMode:    normalizeTriggerMode(firstQuery(c, "trigger_mode", "triggerMode")),
		CountryCode:    strings.ToUpper(strings.TrimSpace(firstQuery(c, "country_code", "countryCode"))),
	}
	var ok bool
	if req.RegionID, ok = optionalInt64(c, "region_id", "regionId"); !ok {
		response.BadRequest(c, "区域 ID 不正确")
		return pendingQuery{}, false
	}
	if req.CountryID, ok = optionalInt64(c, "country_id", "countryId"); !ok {
		response.BadRequest(c, "国家 ID 不正确")
		return pendingQuery{}, false
	}
	if req.UserID, ok = optionalInt64(c, "user_id", "userId"); !ok {
		response.BadRequest(c, "主播用户 ID 不正确")
		return pendingQuery{}, false
	}
	if raw := strings.TrimSpace(firstQuery(c, "role", "settlement_role", "settlementRole")); raw != "" && strings.ToLower(raw) != "all" && req.Role == "" {
		response.BadRequest(c, "结算角色不正确")
		return pendingQuery{}, false
	}
	if raw := strings.TrimSpace(firstQuery(c, "settlement_type", "settlementType")); raw != "" && strings.ToLower(raw) != "all" && req.SettlementType == "" {
		response.BadRequest(c, "结算类型不正确")
		return pendingQuery{}, false
	}
	if raw := strings.TrimSpace(firstQuery(c, "trigger_mode", "triggerMode")); raw != "" && strings.ToLower(raw) != "all" && req.TriggerMode == "" {
		response.BadRequest(c, "触发方式不正确")
		return pendingQuery{}, false
	}
	return normalizePendingQuery(req), true
}

func optionalInt64(c *gin.Context, keys ...string) (int64, bool) {
	value := strings.TrimSpace(firstQuery(c, keys...))
	if value == "" {
		return 0, true
	}
	parsed, err := strconv.ParseInt(value, 10, 64)
	return parsed, err == nil && parsed >= 0
}

func optionalUint64(c *gin.Context, keys ...string) (uint64, bool) {
	value := strings.TrimSpace(firstQuery(c, keys...))
	if value == "" {
		return 0, true
	}
	parsed, err := strconv.ParseUint(value, 10, 64)
	return parsed, err == nil
}

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