import {
  listAdminWorkerOrderFeedbacks as listWorkerOrderFeedbacksForAdmin,
  resolveWorkerOrderFeedback,
} 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 { publishWorkOrderRealtimeChange } from '../realtime/realtime-event-service.js'
import { mapWorkOrderAdmin, mapWorkerOrderFeedback } from './mappers.js'

export async function listAdminWorkerOrderFeedbacks(query: JsonObject = {}) {
  const status = String(query.status || 'pending').trim()
  const normalizedStatus = ['pending', 'resolved'].includes(status) ? status : 'pending'
  return {
    items: (await listWorkerOrderFeedbacksForAdmin(normalizedStatus)).map(mapWorkerOrderFeedback),
  }
}

export async function resolveAdminWorkerOrderFeedback(
  feedbackId: number | string,
  payload: JsonObject = {},
  actorName = '',
) {
  const reply = String(payload.reply || '').trim()
  if (!reply) {
    throw createHttpError('请填写处理回复', {
      statusCode: 400,
      errorCode: 'worker_order_feedback_reply_required',
    })
  }
  const result = await resolveWorkerOrderFeedback({
    feedbackId: Number(feedbackId),
    reply,
    actorName,
    now: nowIso(),
  })
  if (result.failureReason === 'not_found') {
    throw createHttpError('问题反馈不存在', {
      statusCode: 404,
      errorCode: 'worker_order_feedback_not_found',
    })
  }
  if (result.failureReason === 'not_pending') {
    throw createHttpError('该问题反馈已处理，请刷新后重试', {
      statusCode: 409,
      errorCode: 'worker_order_feedback_not_pending',
    })
  }
  if (!result.feedback || !result.order) {
    throw createHttpError('问题反馈处理失败', {
      statusCode: 409,
      errorCode: 'worker_order_feedback_resolve_failed',
    })
  }
  await resolveAdminNotificationEntity(
    'worker_order_feedback',
    Number(result.feedback.id),
    'resolved',
  )
  const workerId = Number(result.feedback.worker_id)
  publishWorkOrderRealtimeChange({
    workOrderId: Number(result.order.id),
    workerIds: workerId > 0 ? [workerId] : [],
  })
  return {
    feedback: mapWorkerOrderFeedback(result.feedback),
    order: mapWorkOrderAdmin(result.order),
  }
}
