import { isFriendGiftAcceptanceMode } from '../../domain/work-order-acceptance-mode.js'
import { submitWorkOrderGiftMaterial } 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 {
  mapWorkOrderForWorker,
  normalizeUploadedFiles,
  resolveWorkerPermissions,
} from './mappers.js'
import { publishWorkOrderParticipantChange } from './worker-order-realtime-service.js'
import {
  getRequiredWorkOrder,
  getRequiredWorker,
  requireActiveWorkerSession,
  type WorkerSession,
} from './worker-session-context-service.js'

/** 打手本人资料的固定字段：昵称/ID/区服必填，系统选填（安卓/苹果）。 */
const BOOSTER_MATERIAL_REQUIRED_FIELDS = [
  { key: 'gameNickname', label: '游戏昵称' },
  { key: 'gameId', label: '游戏ID' },
  { key: 'serverZone', label: '区服' },
] as const

/** 好友赠送模式：打手接单后提交本人游戏资料与主页截图，等待后台核对并添加好友。 */
export async function submitWorkerOrderGiftMaterial(
  workOrderId: number | string,
  payload: JsonObject = {},
  session: WorkerSession,
) {
  requireActiveWorkerSession(session)
  const workOrder = await getRequiredWorkOrder(workOrderId)
  const worker = await getRequiredWorker(session.workerId)
  if (!isFriendGiftAcceptanceMode(workOrder.acceptance_mode)) {
    throw createHttpError('该订单不需要提交好友赠送资料', {
      statusCode: 409,
      errorCode: 'work_order_gift_mode_invalid',
    })
  }
  if (Number(workOrder.assigned_worker_id || 0) !== Number(session.workerId)) {
    throw createHttpError('只能操作自己的订单', {
      statusCode: 403,
      errorCode: 'work_order_owner_required',
    })
  }

  const now = nowIso()
  const fieldsPayload =
    payload.fields && typeof payload.fields === 'object' && !Array.isArray(payload.fields)
      ? (payload.fields as Record<string, unknown>)
      : {}
  const fields: Record<string, string> = {}
  for (const field of BOOSTER_MATERIAL_REQUIRED_FIELDS) {
    const value = String(fieldsPayload[field.key] ?? '').trim()
    if (!value) {
      throw createHttpError(`请填写${field.label}`, {
        statusCode: 400,
        errorCode: 'work_order_gift_material_field_required',
      })
    }
    fields[field.key] = value
  }
  const system = String(fieldsPayload.system ?? '').trim()
  if (system) fields.system = system

  const note = String(payload.note || '').trim()
  if (note.length > 200) {
    throw createHttpError('备注不能超过 200 个字符', {
      statusCode: 400,
      errorCode: 'work_order_gift_material_note_too_long',
    })
  }
  const screenshots = normalizeUploadedFiles(payload.screenshots)
  if (screenshots.length === 0) {
    throw createHttpError('请上传主页截图', {
      statusCode: 400,
      errorCode: 'work_order_gift_material_screenshot_required',
    })
  }

  const { order, failureReason } = await submitWorkOrderGiftMaterial({
    workOrderId: Number(workOrder.id),
    workerId: Number(session.workerId),
    boosterMaterialJson: JSON.stringify({
      fields,
      screenshots,
      note,
      submittedAt: now,
    }),
    now,
  })
  if (failureReason === 'work_order_gift_phase_invalid') {
    throw createHttpError('当前阶段不能提交资料，请刷新后重试', {
      statusCode: 409,
      errorCode: 'work_order_gift_phase_invalid',
    })
  }
  if (failureReason === 'work_order_status_invalid') {
    throw createHttpError('当前订单状态不能提交资料', {
      statusCode: 409,
      errorCode: 'work_order_gift_status_invalid',
    })
  }
  if (failureReason === 'work_order_owner_required') {
    throw createHttpError('只能操作自己的订单', {
      statusCode: 403,
      errorCode: 'work_order_owner_required',
    })
  }
  if (!order) {
    throw createHttpError('提交好友赠送资料失败，请稍后重试', {
      statusCode: 409,
      errorCode: 'work_order_gift_material_submit_failed',
    })
  }
  await publishWorkOrderParticipantChange(Number(workOrder.id), {
    workerIds: [Number(session.workerId)],
  })
  return {
    order: mapWorkOrderForWorker(order, resolveWorkerPermissions(worker)),
  }
}
