import { WORK_ORDER_STATUS } from '../../domain/work-order-status.js'
import { listWorkOrders, listWorkerUsers } from '../../repositories/worker-platform/index.js'
import { publishWorkerHallRealtimeRefresh } from '../realtime/realtime-event-service.js'
import { getWorkerHallConfig, saveWorkerHallConfig } from './worker-hall-config-service.js'

export async function getAdminWorkerPlatformSummary() {
  const hallConfig = getWorkerHallConfig()
  const [pendingWorkers, pendingMaterial, openOrders, visibleOpenOrders, inProgressOrders] =
    await Promise.all([
      listWorkerUsers({ page: 1, pageSize: 1, status: 'pending_review' }),
      listWorkOrders({ page: 1, pageSize: 1, statuses: [WORK_ORDER_STATUS.PENDING_MATERIAL] }),
      listWorkOrders({
        page: 1,
        pageSize: 1,
        statuses: [WORK_ORDER_STATUS.OPEN],
        excludeFilledSharing: true,
      }),
      listWorkOrders({
        page: 1,
        pageSize: 1,
        statuses: [WORK_ORDER_STATUS.OPEN],
        hallCandidateLimit: hallConfig.maxVisibleOrders,
        hallCategoryLimits: hallConfig.categoryMaxVisibleOrders,
        excludeFilledSharing: true,
      }),
      listWorkOrders({
        page: 1,
        pageSize: 1,
        statuses: [WORK_ORDER_STATUS.IN_PROGRESS],
        useOperationalStatus: true,
      }),
    ])
  return {
    pendingWorkerCount: pendingWorkers.total,
    pendingMaterialCount: pendingMaterial.total,
    openOrderCount: visibleOpenOrders.total,
    queuedHallOrderCount: Math.max(0, openOrders.total - visibleOpenOrders.total),
    hallMaxVisibleOrders: hallConfig.maxVisibleOrders,
    inProgressOrderCount: inProgressOrders.total,
  }
}

export async function getAdminWorkerHallConfig() {
  const config = getWorkerHallConfig()
  const [openOrders, visibleOpenOrders] = await Promise.all([
    listWorkOrders({
      page: 1,
      pageSize: 1,
      statuses: [WORK_ORDER_STATUS.OPEN],
      excludeFilledSharing: true,
    }),
    listWorkOrders({
      page: 1,
      pageSize: 1,
      statuses: [WORK_ORDER_STATUS.OPEN],
      hallCandidateLimit: config.maxVisibleOrders,
      hallCategoryLimits: config.categoryMaxVisibleOrders,
      excludeFilledSharing: true,
    }),
  ])
  return {
    ...config,
    visibleOrderCount: visibleOpenOrders.total,
    queuedOrderCount: Math.max(0, openOrders.total - visibleOpenOrders.total),
  }
}

export async function saveAdminWorkerHallConfig(rawValue: unknown) {
  await saveWorkerHallConfig(rawValue)
  const config = await getAdminWorkerHallConfig()
  publishWorkerHallRealtimeRefresh()
  return config
}
