package hostsalarysettlement

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

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

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

type Handler struct {
	service *Service
}

func New(walletDB *sql.DB, userDB *sql.DB) *Handler {
	return &Handler{service: NewService(walletDB, userDB)}
}

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 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,
		AgencyOwnerUserID: agencyOwnerUserID,
		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 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 ""
}
