import { WORK_ORDER_STATUS } from '../../domain/work-order-status.js'
import {
  listOverdueWorkOrders,
  settleOverdueWorkOrder,
} from '../../repositories/worker-platform/index.js'
import { nowIso } from '../../utils/time.js'
import {
  publishWorkerWalletRealtimeChange,
  publishWorkOrderRealtimeChange,
} from '../realtime/realtime-event-service.js'
import { normalizeWorkOrderTimeoutPolicy } from './work-order-timeout-policy.js'

export async function settleOverdueWorkOrders(options: { limit?: number; workerId?: number } = {}) {
  const overdue = await listOverdueWorkOrders({
    limit: Math.max(1, Number(options.limit || 50)),
    workerId: Number(options.workerId || 0),
  })
  let processedCount = 0
  let skippedCount = 0
  for (const workOrder of overdue) {
    const result = await settleOverdueWorkOrder({
      workOrderId: workOrder.id,
      policy: normalizeWorkOrderTimeoutPolicy(workOrder.timeout_policy),
      now: nowIso(),
    })
    if (result.order) {
      processedCount += 1
      publishWorkOrderRealtimeChange({
        workOrderId: Number(workOrder.id),
        workerIds: Number(workOrder.assigned_worker_id)
          ? [Number(workOrder.assigned_worker_id)]
          : [],
        hallChanged: result.order.status === WORK_ORDER_STATUS.OPEN,
      })
      if (Number(workOrder.assigned_worker_id)) {
        publishWorkerWalletRealtimeChange(Number(workOrder.assigned_worker_id))
      }
    } else {
      skippedCount += 1
    }
  }
  return {
    checkedCount: overdue.length,
    processedCount,
    skippedCount,
  }
}
