package hostwithdrawal

import (
	"database/sql"
	"errors"
	"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(adminDB *sql.DB, walletDB *sql.DB, userDB *sql.DB) *Handler {
	return &Handler{service: NewService(adminDB, walletDB, userDB)}
}

func (h *Handler) List(c *gin.Context) {
	query, ok := parseListQuery(c, appctx.FromContext(c.Request.Context()))
	if !ok {
		return
	}
	items, total, err := h.service.List(c.Request.Context(), query)
	if err != nil {
		if errors.Is(err, errInvalidArgument) {
			response.BadRequest(c, "主播提现筛选参数不正确")
			return
		}
		response.ServerError(c, "获取主播提现列表失败")
		return
	}
	response.OK(c, response.Page{Items: items, Page: query.Page, PageSize: query.PageSize, Total: total})
}

func parseListQuery(c *gin.Context, defaultAppCode string) (listQuery, bool) {
	options := shared.ListOptions(c)
	startAtMS, ok := optionalInt64(c, "start_at_ms", "startAtMs")
	if !ok {
		response.BadRequest(c, "开始时间不正确")
		return listQuery{}, false
	}
	endAtMS, ok := optionalInt64(c, "end_at_ms", "endAtMs")
	if !ok {
		response.BadRequest(c, "结束时间不正确")
		return listQuery{}, false
	}
	query, err := normalizeListQuery(listQuery{
		Page:       options.Page,
		PageSize:   options.PageSize,
		AppCode:    firstNonEmpty(c.Query("app_code"), c.Query("appCode"), defaultAppCode),
		RecordType: firstNonEmpty(c.Query("record_type"), c.Query("recordType")),
		Identity:   firstNonEmpty(c.Query("identity"), c.Query("salary_asset_type"), c.Query("salaryAssetType")),
		Status:     options.Status,
		Keyword:    options.Keyword,
		StartAtMS:  startAtMS,
		EndAtMS:    endAtMS,
	})
	if err != nil {
		response.BadRequest(c, "主播提现筛选参数不正确")
		return listQuery{}, false
	}
	return query, true
}

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

func queryValues(c *gin.Context, keys ...string) []string {
	values := make([]string, 0, len(keys))
	for _, key := range keys {
		values = append(values, c.Query(key))
	}
	return values
}
