import {
  listAdminWorkerCancelRequests as listWorkerCancelRequestsForAdmin,
  reviewWorkerCancelRequest,
} from '../../repositories/worker-platform/index.js'
import type { JsonObject } from '../../types/json.js'
import { createHttpError } from '../../utils/http.js'
import { nowIso } from '../../utils/time.js'
import { resolveAdminNotificationEntity } from '../admin/admin-notification-service.js'
import {
  publishWorkerWalletRealtimeChange,
  publishWorkOrderRealtimeChange,
} from '../realtime/realtime-event-service.js'
import { mapWorkOrderAdmin, mapWorkerCancelRequest } from './mappers.js'

export async function listAdminWorkerCancelRequests(query: JsonObject = {}) {
  const status = String(query.status || 'pending').trim()
  const normalizedStatus = ['pending', 'approved', 'rejected'].includes(status) ? status : 'pending'
  return {
    items: (await listWorkerCancelRequestsForAdmin(normalizedStatus)).map(mapWorkerCancelRequest),
  }
}

export async function reviewAdminWorkerCancelRequest(
  requestId: number | string,
  payload: JsonObject = {},
  actorName = '',
) {
  const approved = payload.approved === true || String(payload.action || '').trim() === 'approve'
  const reviewNote = String(payload.reviewNote || payload.note || '').trim()
  if (!reviewNote) {
    throw createHttpError('请填写审核备注', {
      statusCode: 400,
      errorCode: 'worker_cancel_request_review_note_required',
    })
  }
  const result = await reviewWorkerCancelRequest({
    requestId: Number(requestId),
    approved,
    reviewNote,
    actorName,
    now: nowIso(),
  })
  if (result.failureReason === 'request_not_found') {
    throw createHttpError('打手退单申请不存在', {
      statusCode: 404,
      errorCode: 'worker_cancel_request_not_found',
    })
  }
  if (result.failureReason === 'request_not_pending') {
    throw createHttpError('该打手退单申请已审核，请刷新后重试', {
      statusCode: 409,
      errorCode: 'worker_cancel_request_not_pending',
    })
  }
  if (!result.request || !result.order) {
    throw createHttpError('订单状态已变化，无法审核该打手退单申请', {
      statusCode: 409,
      errorCode: 'worker_cancel_request_target_changed',
    })
  }
  await resolveAdminNotificationEntity(
    'worker_cancel_request',
    Number(result.request.id),
    approved ? 'approved' : 'rejected',
  )
  const workerId = Number(result.request.worker_id)
  publishWorkOrderRealtimeChange({
    workOrderId: Number(result.order.id),
    workerIds: workerId > 0 ? [workerId] : [],
    hallChanged: approved,
  })
  if (approved && workerId > 0) publishWorkerWalletRealtimeChange(workerId)
  return {
    request: mapWorkerCancelRequest(result.request),
    order: mapWorkOrderAdmin(result.order),
    approved,
    releasedDepositAmount: result.releasedDepositAmount,
    levelChanged: result.levelChanged,
    accountDisabled: result.accountDisabled,
  }
}
