import {
  listAdminWorkerLeaderboard,
  type AdminLeaderboardPeriod,
} from '../../repositories/worker-platform/index.js'
import type { JsonObject } from '../../types/json.js'

const PERIODS: AdminLeaderboardPeriod[] = ['all', 'daily', 'weekly', 'monthly']
const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/
const MAX_CUSTOM_RANGE_DAYS = 366

function normalizeDate(value: unknown): string | null {
  const text = String(value || '').trim()
  return DATE_PATTERN.test(text) ? text : null
}

/** 后台接单排行榜读取：预置周期或自定义日期区间（含起止日）+ 完成单数与奖励汇总。 */
export async function getAdminWorkerLeaderboard(query: JsonObject = {}) {
  const requested = String(query.period || 'all').trim() as AdminLeaderboardPeriod
  const period = PERIODS.includes(requested) ? requested : 'all'
  const limit = Number(query.limit || 50)
  const fromDate = normalizeDate(query.from)
  const toDate = normalizeDate(query.to)
  if ((fromDate || toDate) && !(fromDate && toDate)) {
    throw new Error('自定义区间需要同时提供开始与结束日期')
  }
  if (fromDate && toDate) {
    const fromTime = new Date(`${fromDate}T00:00:00Z`).getTime()
    const toTime = new Date(`${toDate}T00:00:00Z`).getTime()
    if (fromTime > toTime) {
      throw new Error('自定义区间的开始日期不能晚于结束日期')
    }
    if ((toTime - fromTime) / 86400000 > MAX_CUSTOM_RANGE_DAYS) {
      throw new Error('自定义区间最长不能超过一年')
    }
  }
  const items = await listAdminWorkerLeaderboard({ period, limit, fromDate, toDate })
  return { period: fromDate && toDate ? 'custom' : period, from: fromDate, to: toDate, items }
}
