import { query } from '../../db/client.js'
import { nowIso } from '../../utils/time.js'

type JsonObject = Record<string, any>

export async function getAdminDashboardSummary() {
  const todayPrefix = nowIso().slice(0, 10)
  const result = await query(
    `
      SELECT
        (SELECT COUNT(*)::int FROM orders WHERE to_char(created_at AT TIME ZONE 'Asia/Shanghai', 'YYYY-MM-DD') = $1) AS today_orders,
        (
          SELECT COUNT(*)::int
          FROM fulfillment_tasks
          WHERE task_status IN ('paid', 'link_generated')
             OR (inventory_status = 'reserved' AND task_status NOT IN ('claimed', 'role_confirmed', 'redeeming', 'redeemed', 'closed', 'expired'))
        ) AS paid_pending_claim,
        (
          SELECT COUNT(*)::int
          FROM fulfillment_tasks
          WHERE task_status IN ('claimed', 'role_confirmed', 'redeeming')
        ) AS claiming_tasks,
        (
          SELECT COUNT(*)::int
          FROM fulfillment_tasks
          WHERE task_status = 'redeemed'
            AND to_char(updated_at AT TIME ZONE 'Asia/Shanghai', 'YYYY-MM-DD') = $1
        ) AS redeemed_today,
        (
          SELECT COUNT(*)::int
          FROM fulfillment_tasks
          WHERE task_status IN ('retry_pending', 'manual_review', 'waiting_inventory')
        ) AS abnormal_tasks,
        (
          SELECT COUNT(DISTINCT sku_code)::int
          FROM inventory_items
          WHERE status = 'available'
        ) AS sku_with_inventory
    `,
    [todayPrefix],
  )
  const summary: JsonObject = result.rows[0] || {}

  return {
    todayOrders: Number(summary?.today_orders || 0),
    paidPendingClaim: Number(summary?.paid_pending_claim || 0),
    claimingTasks: Number(summary?.claiming_tasks || 0),
    redeemedToday: Number(summary?.redeemed_today || 0),
    abnormalTasks: Number(summary?.abnormal_tasks || 0),
    skuWithInventory: Number(summary?.sku_with_inventory || 0),
  }
}
