import {
  getWorkOrderStatistics,
  listWorkOrderEventsByOrderId,
  listWorkOrderSharesByOrderIds,
  listWorkOrders,
  sumPendingUnfreezeByOrderIds,
} from '../../repositories/worker-platform/index.js'
import type { JsonObject } from '../../types/json.js'
import {
  normalizeDateString,
  normalizePage,
  normalizePageSize,
} from '../admin/admin-query-utils.js'
import {
  mapWorkOrderAdmin,
  mapWorkOrderEvents,
  normalizeBoolean,
  normalizeOptionalId,
  normalizeStatuses,
} from './mappers.js'
import { getRequiredWorkOrder } from './worker-session-context-service.js'

export async function getAdminWorkOrderEvents(workOrderId: number | string) {
  await getRequiredWorkOrder(workOrderId)
  const events = await listWorkOrderEventsByOrderId(workOrderId)
  return { items: await mapWorkOrderEvents(events, { includeWorkerSummary: true }) }
}

export async function listAdminWorkOrders(query: JsonObject = {}) {
  const page = normalizePage(query.page)
  const pageSize = normalizePageSize(query.pageSize)
  const workOrderId = normalizeOptionalId(query.workOrderId ?? query.work_order_id) || 0
  const categoryId = normalizeOptionalId(query.categoryId ?? query.category_id) || 0
  const workerId = normalizeOptionalId(query.workerId ?? query.worker_id) || 0
  const workerLevelIds = normalizeStatuses(query.workerLevelIds ?? query.worker_level_ids)
    .map(normalizeOptionalId)
    .filter((levelId): levelId is number => levelId !== null)
  const statuses = normalizeStatuses(query.status)
  const vipEvidencePending = normalizeBoolean(query.vipEvidencePending, false)
  const createdFrom = normalizeDateString(query.createdFrom)
  const createdTo = normalizeDateString(query.createdTo)
  const acceptanceMode = String(query.acceptanceMode || '').trim()
  const giftPhase = String(query.giftPhase || '').trim()
  const filters = {
    statuses,
    workOrderId,
    categoryId,
    keyword: String(query.keyword || '').trim(),
    workerSharingId: workerId,
    workerLevelIds,
    vipEvidencePending,
    ...(acceptanceMode ? { acceptanceMode } : {}),
    ...(giftPhase ? { giftPhase } : {}),
    useOperationalStatus: true,
    ...(createdFrom ? { createdFrom } : {}),
    ...(createdTo ? { createdTo } : {}),
  }
  const { items, total } = await listWorkOrders({ page, pageSize, ...filters })
  const statistics = await getWorkOrderStatistics(filters)
  const pendingUnfreezeByOrderId = await sumPendingUnfreezeByOrderIds(
    items.map((item) => Number(item.id)),
  )
  const shares = await listWorkOrderSharesByOrderIds(items.map((item) => Number(item.id)))
  const sharesByOrderId = new Map<number, typeof shares>()
  for (const share of shares) {
    const orderId = Number(share.work_order_id)
    const current = sharesByOrderId.get(orderId) || []
    current.push(share)
    sharesByOrderId.set(orderId, current)
  }
  return {
    items: items.map((item) => ({
      ...mapWorkOrderAdmin(item, sharesByOrderId.get(Number(item.id)) || []),
      pendingUnfreezeAmount: pendingUnfreezeByOrderId.get(Number(item.id)) || 0,
    })),
    pagination: { page, pageSize, total },
    statistics,
  }
}
