import {
  completeWorkOrderGiftCooldown,
  confirmWorkOrderFriendAdded,
  resetWorkOrderGiftMaterial,
} from '../../repositories/worker-platform/index.js'
import { publishWorkOrderRealtimeChange } from '../realtime/realtime-event-service.js'
import { mapWorkOrderAdmin } from './mappers.js'
import { getRequiredWorkOrder } from './worker-session-context-service.js'
import { nowIso } from '../../utils/time.js'
import { createHttpError } from '../../utils/http.js'

/** 后台核对打手资料并添加游戏好友后确认，开始 N 小时赠送冷却。 */
export async function confirmAdminWorkOrderFriendAdded(
  workOrderId: number | string,
  actorName = '',
) {
  const workOrder = await getRequiredWorkOrder(workOrderId)
  const { order, failureReason } = await confirmWorkOrderFriendAdded({
    workOrderId: Number(workOrder.id),
    actorName,
    now: nowIso(),
  })
  if (failureReason === 'work_order_gift_phase_invalid') {
    throw createHttpError('当前阶段不能确认加好友，请刷新后重试', {
      statusCode: 409,
      errorCode: 'work_order_friend_confirm_phase_invalid',
    })
  }
  if (!order) {
    throw createHttpError('确认加好友失败，订单可能已变化', {
      statusCode: 409,
      errorCode: 'work_order_friend_confirm_failed',
    })
  }
  const workerId = Number(order.assigned_worker_id || 0)
  publishWorkOrderRealtimeChange({
    workOrderId: Number(order.id),
    workerIds: workerId > 0 ? [workerId] : [],
  })
  return { order: mapWorkOrderAdmin(order) }
}

/** 客服手动结束好友赠送冷却，让打手立即可以提交赠送凭证。 */
export async function completeAdminWorkOrderGiftCooldown(
  workOrderId: number | string,
  payload: { note?: unknown } = {},
  actorName = '',
) {
  const workOrder = await getRequiredWorkOrder(workOrderId)
  const { order, failureReason } = await completeWorkOrderGiftCooldown({
    workOrderId: Number(workOrder.id),
    note: String(payload.note || '').trim(),
    actorName,
    now: nowIso(),
  })
  if (failureReason === 'work_order_gift_phase_invalid') {
    throw createHttpError('当前订单不在好友赠送冷却中，请刷新后重试', {
      statusCode: 409,
      errorCode: 'work_order_gift_cooldown_phase_invalid',
    })
  }
  if (failureReason === 'work_order_gift_cooldown_completed') {
    throw createHttpError('好友赠送冷却已结束，无需手动操作', {
      statusCode: 409,
      errorCode: 'work_order_gift_cooldown_already_completed',
    })
  }
  if (failureReason === 'work_order_status_invalid') {
    throw createHttpError('当前订单状态不能结束赠送冷却', {
      statusCode: 409,
      errorCode: 'work_order_gift_cooldown_status_invalid',
    })
  }
  if (!order) {
    throw createHttpError('结束赠送冷却失败，订单可能已变化', {
      statusCode: 409,
      errorCode: 'work_order_gift_cooldown_complete_failed',
    })
  }
  const workerId = Number(order.assigned_worker_id || 0)
  publishWorkOrderRealtimeChange({
    workOrderId: Number(order.id),
    workerIds: workerId > 0 ? [workerId] : [],
  })
  return { order: mapWorkOrderAdmin(order) }
}

/** 打手资料有误或误确认好友时，重置资料让打手重新提交（冷却与好友时间清零）。 */
export async function resetAdminWorkOrderGiftMaterial(
  workOrderId: number | string,
  payload: { note?: unknown } = {},
  actorName = '',
) {
  const workOrder = await getRequiredWorkOrder(workOrderId)
  const note = String(payload.note || '').trim()
  const { order, failureReason } = await resetWorkOrderGiftMaterial({
    workOrderId: Number(workOrder.id),
    note,
    actorName,
    now: nowIso(),
  })
  if (failureReason === 'work_order_gift_phase_invalid') {
    throw createHttpError('当前阶段没有可重置的打手资料', {
      statusCode: 409,
      errorCode: 'work_order_gift_reset_phase_invalid',
    })
  }
  if (failureReason === 'work_order_status_invalid') {
    throw createHttpError('当前订单状态不能重置资料', {
      statusCode: 409,
      errorCode: 'work_order_gift_reset_status_invalid',
    })
  }
  if (!order) {
    throw createHttpError('重置打手资料失败，订单可能已变化', {
      statusCode: 409,
      errorCode: 'work_order_gift_reset_failed',
    })
  }
  const workerId = Number(order.assigned_worker_id || 0)
  publishWorkOrderRealtimeChange({
    workOrderId: Number(order.id),
    workerIds: workerId > 0 ? [workerId] : [],
  })
  return { order: mapWorkOrderAdmin(order) }
}
