import { WORK_ORDER_STATUS } from '../../domain/work-order-status.js'
import {
  createWorkOrderEvent,
  listWorkOrderShares,
  updateWorkOrder,
} 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 { publishWorkOrderRealtimeChange } from '../realtime/realtime-event-service.js'
import {
  mapWorkOrderAdmin,
  mapWorkOrderShare,
  normalizeAmountFen,
  normalizeBoolean,
  normalizePositiveInteger,
} from './mappers.js'
import { resolveSharingQuantity } from './admin-worker-catalog-service.js'
import { getRequiredWorkOrder } from './worker-session-context-service.js'

export async function getAdminWorkOrderSharing(workOrderId: number | string) {
  const workOrder = await getRequiredWorkOrder(workOrderId)
  const shares = await listWorkOrderShares(workOrder.id)
  return {
    order: mapWorkOrderAdmin(workOrder, shares),
    shares: shares.map(mapWorkOrderShare),
  }
}

export async function updateAdminWorkOrderSharing(
  workOrderId: number | string,
  payload: JsonObject = {},
  actorName = '',
) {
  const workOrder = await getRequiredWorkOrder(workOrderId)
  if (!mapWorkOrderAdmin(workOrder).capabilities.canConfigureSharing) {
    throw createHttpError('只有待完善、未分配或待抢单的工单可以配置拼单', {
      statusCode: 409,
      errorCode: 'work_order_sharing_config_status_invalid',
    })
  }
  const enabled = normalizeBoolean(
    payload.enabled ?? payload.sharingEnabled ?? payload.sharing_enabled,
    false,
  )
  const unitReward = normalizeAmountFen(
    payload.unitReward ?? payload.sharingUnitReward ?? payload.sharingUnitRewardYuan,
    0,
  )
  const totalAmount = normalizeAmountFen(
    payload.totalAmount ?? payload.sharingTotalAmount ?? payload.sharingTotalAmountYuan,
    0,
  )
  const totalQuantity = resolveSharingQuantity(
    totalAmount,
    normalizePositiveInteger(
      payload.totalQuantity ?? payload.sharingTotalQuantity ?? payload.sharing_total_quantity,
      1,
    ),
    unitReward,
  )
  const resolvedTotalAmount = totalAmount > 0 ? totalAmount : unitReward * totalQuantity
  const now = nowIso()
  const updated = await updateWorkOrder(workOrder.id, {
    sharing_enabled: enabled,
    sharing_total_quantity: totalQuantity,
    sharing_unit_reward: unitReward,
    reward_amount: enabled ? resolvedTotalAmount : workOrder.reward_amount,
    updated_at: now,
  })
  await createWorkOrderEvent({
    workOrderId: workOrder.id,
    actorType: 'admin',
    actorId: actorName,
    eventType: 'sharing_config_updated',
    fromStatus: workOrder.status,
    toStatus: updated?.status || workOrder.status,
    payloadJson: JSON.stringify({
      enabled,
      totalQuantity,
      unitReward,
      totalAmount: resolvedTotalAmount,
    }),
    now,
  })
  publishWorkOrderRealtimeChange({
    workOrderId: Number(workOrder.id),
    hallChanged: workOrder.status === WORK_ORDER_STATUS.OPEN,
  })
  return { order: mapWorkOrderAdmin(updated || workOrder) }
}
