package report

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

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

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

type Handler struct {
	service *Service
}

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

func (h *Handler) ListReports(c *gin.Context) {
	query, ok := parseListQuery(c)
	if !ok {
		return
	}
	items, total, err := h.service.ListReports(c.Request.Context(), appctx.FromContext(c.Request.Context()), query)
	if err != nil {
		response.ServerError(c, "获取举报列表失败")
		return
	}
	response.OK(c, response.Page{Items: items, Page: query.Page, PageSize: query.PageSize, Total: total})
}

func parseListQuery(c *gin.Context) (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
	}
	if startAtMS > 0 && endAtMS > 0 && startAtMS >= endAtMS {
		response.BadRequest(c, "时间区间不正确")
		return listQuery{}, false
	}
	return normalizeListQuery(listQuery{
		Page:       options.Page,
		PageSize:   options.PageSize,
		Keyword:    options.Keyword,
		TargetType: firstQuery(c, "target_type", "targetType"),
		ReportType: firstQuery(c, "report_type", "reportType"),
		StartAtMS:  startAtMS,
		EndAtMS:    endAtMS,
	}), 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)
	if err != nil || parsed < 0 {
		return 0, false
	}
	return parsed, true
}

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