import {
  getWorkOrderById,
  getWorkerUserById,
  type WorkOrderRow,
  type WorkerUserRow,
} from '../../repositories/worker-platform/index.js'
import { createHttpError } from '../../utils/http.js'

export type WorkerSession = {
  sessionId: string
  workerId: number
  username: string
  status: string
  expiresAt: string
  sessionVersion: number
}

export function requireActiveWorkerSession(session: WorkerSession | null | undefined) {
  if (session?.status === 'active') return

  throw createHttpError('接单账号尚未通过审核', {
    statusCode: 403,
    errorCode: 'worker_not_active',
  })
}

export async function getRequiredWorker(workerId: number | string): Promise<WorkerUserRow> {
  const worker = await getWorkerUserById(workerId)
  if (!worker) {
    throw createHttpError('接单账号不存在', {
      statusCode: 404,
      errorCode: 'worker_not_found',
    })
  }
  return worker
}

export async function getRequiredWorkOrder(workOrderId: number | string): Promise<WorkOrderRow> {
  const workOrder = await getWorkOrderById(workOrderId)
  if (!workOrder) {
    throw createHttpError('接单订单不存在', {
      statusCode: 404,
      errorCode: 'work_order_not_found',
    })
  }
  return workOrder
}
