import type { WorkerDepositUnfreezeRow } from '../../repositories/worker-platform/index.js'
import {
  countWorkerAcceptedOrders,
  countWorkerActiveOrders,
  countWorkerTimeoutEvents,
  getWorkerOrderOverview,
  listWorkerDepositUnfreezes,
  listWorkerWalletLedgers,
} from '../../repositories/worker-platform/index.js'
import type { JsonObject } from '../../types/json.js'
import { normalizePage, normalizePageSize } from '../admin/admin-query-utils.js'
import { mapWalletLedger, mapWorkerUser } from './mappers.js'
import { getRequiredWorker } from './worker-session-context-service.js'

/** 管理端打手详情：聚合账号钱包、接单统计与订单概览，全部只读。 */
export async function getAdminWorkerDetail(workerId: number | string) {
  const worker = await getRequiredWorker(workerId)
  const [activeOrderCount, acceptedOrderCount, timeoutOrderCount, orderOverview] =
    await Promise.all([
      countWorkerActiveOrders(worker.id),
      countWorkerAcceptedOrders(worker.id),
      countWorkerTimeoutEvents(worker.id),
      getWorkerOrderOverview(worker.id),
    ])
  return {
    worker: mapWorkerUser(worker),
    summary: { activeOrderCount, acceptedOrderCount, timeoutOrderCount },
    orderOverview,
  }
}

export async function listAdminWorkerWalletLedgers(
  workerId: number | string,
  payload: JsonObject = {},
) {
  const worker = await getRequiredWorker(workerId)
  const page = normalizePage(payload.page)
  const pageSize = normalizePageSize(payload.pageSize)
  const ledgerType = String(payload.ledgerType || payload.ledger_type || '').trim()
  const { items, total } = await listWorkerWalletLedgers({
    page,
    pageSize,
    workerId: Number(worker.id),
    ledgerType,
  })
  return { items: items.map(mapWalletLedger), pagination: { page, pageSize, total } }
}

export async function listAdminWorkerDepositUnfreezes(
  workerId: number | string,
  payload: JsonObject = {},
) {
  const worker = await getRequiredWorker(workerId)
  const page = normalizePage(payload.page)
  const pageSize = normalizePageSize(payload.pageSize)
  const status = String(payload.status || '').trim()
  const { items, total } = await listWorkerDepositUnfreezes({
    workerId: Number(worker.id),
    status,
    page,
    pageSize,
  })
  return {
    items: items.map(mapDepositUnfreeze),
    pagination: { page, pageSize, total },
  }
}

function mapDepositUnfreeze(row: WorkerDepositUnfreezeRow) {
  return {
    id: Number(row.id),
    workerId: Number(row.worker_id),
    workOrderId: Number(row.work_order_id),
    amount: Number(row.amount || 0),
    fundType: row.fund_type || 'legacy_combined',
    status: row.status,
    unfreezeAt: row.unfreeze_at,
    releasedAt: row.released_at || null,
    createdAt: row.created_at,
  }
}
