import { query } from '../../db/client.js'
import type { WorkerDepositUnfreezeRow } from './types.js'

/** 汇总仍在等待解冻的押金，供后台订单扣押金操作展示。 */
export async function sumPendingUnfreezeByOrderIds(
  workOrderIds: number[],
): Promise<Map<number, number>> {
  const totals = new Map<number, number>()
  const uniqueIds = [...new Set(workOrderIds.map(Number).filter((id) => id > 0))]
  if (uniqueIds.length === 0) return totals
  const result = await query<{ work_order_id: number; total: number }>(
    `
      SELECT work_order_id, SUM(amount)::int AS total
      FROM worker_deposit_unfreezes
      WHERE work_order_id = ANY($1::bigint[])
        AND status = 'pending'
        AND fund_type = 'deposit'
      GROUP BY work_order_id
    `,
    [uniqueIds],
  )
  for (const row of result.rows) {
    totals.set(Number(row.work_order_id), Number(row.total || 0))
  }
  return totals
}

export async function listDueDepositUnfreezes({
  limit = 100,
  workerId = 0,
  retroactiveDays = -1,
}: {
  limit?: number
  workerId?: number
  /** >=0 时按当前配置回溯：created_at + retroactiveDays 天也视为到期，配置调小后存量提前释放。 */
  retroactiveDays?: number
}): Promise<WorkerDepositUnfreezeRow[]> {
  const params: unknown[] = []
  let workerClause = ''
  if (workerId > 0) {
    params.push(workerId)
    workerClause = `AND worker_id = $${params.length}`
  }
  let dueClause = 'unfreeze_at <= NOW()'
  if (Number.isFinite(retroactiveDays) && retroactiveDays >= 0) {
    params.push(Math.floor(retroactiveDays))
    dueClause = `(unfreeze_at <= NOW() OR created_at + ($${params.length} * INTERVAL '1 day') <= NOW())`
  }
  params.push(limit)
  const result = await query<WorkerDepositUnfreezeRow>(
    `
      SELECT * FROM worker_deposit_unfreezes
      WHERE status = 'pending' AND ${dueClause} ${workerClause}
      ORDER BY unfreeze_at ASC
      LIMIT $${params.length}
    `,
    params,
  )
  return result.rows
}

/** 管理端按打手列出全部解冻记录（含未到期与已释放），观察待解冻到账进度。 */
export async function listWorkerDepositUnfreezes({
  workerId,
  status = '',
  page = 1,
  pageSize = 20,
}: {
  workerId: number
  status?: string
  page?: number
  pageSize?: number
}): Promise<{ items: WorkerDepositUnfreezeRow[]; total: number }> {
  const params: unknown[] = [Number(workerId)]
  const normalizedStatus = String(status || '').trim()
  let statusClause = ''
  if (normalizedStatus) {
    params.push(normalizedStatus)
    statusClause = ` AND status = $${params.length}`
  }
  const totalResult = await query<{ total: number }>(
    `SELECT COUNT(*)::int AS total FROM worker_deposit_unfreezes WHERE worker_id = $1${statusClause}`,
    params,
  )
  params.push(pageSize, (page - 1) * pageSize)
  const result = await query<WorkerDepositUnfreezeRow>(
    `
      SELECT * FROM worker_deposit_unfreezes
      WHERE worker_id = $1${statusClause}
      ORDER BY unfreeze_at DESC, id DESC
      LIMIT $${params.length - 1} OFFSET $${params.length}
    `,
    params,
  )
  return { items: result.rows, total: Number(totalResult.rows[0]?.total || 0) }
}
