import { WORK_ORDER_STATUS } from '../../domain/work-order-status.js'
import {
  normalizeWorkOrderAcceptanceMode,
  normalizeWorkOrderGiftCooldownHours,
  normalizeWorkOrderGiftCooldownMinutes,
} from '../../domain/work-order-acceptance-mode.js'
import {
  createWorkOrder,
  createWorkOrderEvent,
  getWorkCategoryById,
  listWorkOrdersByPlatformOrderId,
} from '../../repositories/worker-platform/index.js'
import type { JsonObject } from '../../types/json.js'
import { createHttpError } from '../../utils/http.js'
import { randomId } from '../../utils/random.js'
import { nowIso } from '../../utils/time.js'
import {
  getKuaishouIndustrySourceConfig,
  listKuaishouIndustryShopConfigs,
  type KuaishouIndustryShopConfig,
} from '../platforms/kuaishou-industry/source-config-service.js'
import {
  DEFAULT_DEPOSIT_THRESHOLD_AMOUNT,
  mapWorkOrderAdmin,
  normalizeAmountFen,
  normalizeInteger,
  normalizeRequirementFields,
} from './mappers.js'
import { rememberAdminMockCustomShop } from './admin-mock-custom-shop-service.js'
import { ensureWorkerPlatformDefaults } from './worker-platform-defaults.js'
import { normalizeWorkOrderTimeoutPolicy } from './work-order-timeout-policy.js'

export async function createAdminMockWorkOrder(payload: JsonObject = {}) {
  const defaults = await ensureWorkerPlatformDefaults()
  const now = nowIso()
  const input = resolveAdminMockWorkOrderInput(
    payload,
    listKuaishouIndustryShopConfigs(getKuaishouIndustrySourceConfig()),
  )
  const rewardAmount = input.rewardAmount
  const depositThresholdAmount = normalizeAmountFen(
    payload.depositThresholdAmount ?? payload.depositThresholdAmountYuan,
    DEFAULT_DEPOSIT_THRESHOLD_AMOUNT,
  )
  const requiredDepositAmount =
    payload.requiredDepositAmount === undefined
      ? rewardAmount > depositThresholdAmount
        ? rewardAmount
        : 0
      : normalizeAmountFen(payload.requiredDepositAmount, 0)
  const paymentFen = input.paymentAmount
  const requestedCategoryId = Number(payload.categoryId || payload.category_id || 0)
  let categoryId = defaults.category?.id || null
  if (requestedCategoryId > 0) {
    const category = await getWorkCategoryById(requestedCategoryId)
    if (!category || category.status !== 'active') {
      throw createHttpError('所选接单分类不存在或已停用', {
        statusCode: 409,
        errorCode: 'mock_work_order_category_invalid',
      })
    }
    categoryId = Number(category.id)
  }
  const materialComplete = payload.materialComplete === true || payload.materialComplete === 'true'
  const fields = normalizeRequirementFields(payload.fields)
  const { platformOrderId, productName, shop } = input
  // 订单号全局唯一：与自动同步的真实工单也不能撞号，否则打手按单号回填资料会命中多条。
  const existingOrders = await listWorkOrdersByPlatformOrderId(platformOrderId)
  if (existingOrders.length > 0) {
    const existingNo = String(existingOrders[0]?.work_order_no || '').trim()
    throw createHttpError(
      `该订单号已存在工单${existingNo ? `（${existingNo}）` : ''}，请更换订单号`,
      {
        statusCode: 409,
        errorCode: 'mock_work_order_platform_order_exists',
      },
    )
  }
  const material = {
    ...(materialComplete
      ? {
          collect: {
            complete: true,
            submittedAt: now,
            fields: fields.reduce<Record<string, string>>((result, field) => {
              result[field.key] = String(field.mockValue || `${field.label}测试值`)
              return result
            }, {}),
          },
        }
      : {}),
    source: {
      orderAmountFen: paymentFen,
      syncSource: 'mock',
      mock: true,
      provider: 'mock',
      platform: 'mock',
      sellerId: String(shop.sellerId || shop.shopId || '').trim(),
      shopId: String(shop.shopId || shop.sellerId || '').trim(),
      shopName: String(
        shop.customShopName || shop.shopName || shop.shopId || shop.sellerId || '',
      ).trim(),
    },
  }
  const workOrder = await createWorkOrder({
    workOrderNo: randomId('WO'),
    platformOrderId,
    productName,
    categoryId,
    status: materialComplete ? WORK_ORDER_STATUS.UNASSIGNED : WORK_ORDER_STATUS.PENDING_MATERIAL,
    rewardAmount,
    requiredDepositAmount,
    depositThresholdAmount,
    timeoutMinutes: Math.max(0, normalizeInteger(payload.timeoutMinutes, 0)),
    timeoutPolicy: normalizeWorkOrderTimeoutPolicy(payload.timeoutPolicy),
    acceptanceMode: normalizeWorkOrderAcceptanceMode(payload.acceptanceMode),
    giftCooldownHours: normalizeWorkOrderGiftCooldownHours(payload.giftCooldownHours),
    giftCooldownMinutes: normalizeWorkOrderGiftCooldownMinutes(payload.giftCooldownMinutes),
    materialJson: JSON.stringify(material),
    requirementJson: JSON.stringify({ fields }),
    now,
  })
  if (!workOrder) {
    throw createHttpError('接单工单创建失败', {
      statusCode: 500,
      errorCode: 'work_order_create_failed',
    })
  }
  if (input.isCustomShop && shop.shopName) {
    // 自定义店铺录入后沉淀为可选项，下次直接下拉选择。
    await rememberAdminMockCustomShop(shop.shopName)
  }
  await createWorkOrderEvent({
    workOrderId: workOrder.id,
    actorType: 'admin',
    actorId: 'dev_mock',
    eventType: 'mock_created',
    fromStatus: '',
    toStatus: workOrder.status,
    payloadJson: JSON.stringify({
      platformOrderId,
      productName,
      rewardAmount,
      sellerId: String(shop.sellerId || '').trim(),
      shopName: String(shop.shopName || '').trim(),
    }),
    now,
  })
  return { order: mapWorkOrderAdmin(workOrder) }
}

/** 本地 Mock 与真实订单保持相同的关键字段约束，避免生成无法追溯的测试工单。 */
export function resolveAdminMockWorkOrderInput(
  payload: JsonObject,
  shops: KuaishouIndustryShopConfig[],
) {
  const platformOrderId = String(payload.platformOrderId || '').trim()
  if (!platformOrderId) {
    throw createHttpError('请填写订单号', {
      statusCode: 400,
      errorCode: 'mock_work_order_no_required',
    })
  }

  const productName = String(payload.productName || '').trim()
  if (!productName) {
    throw createHttpError('请填写商品名称', {
      statusCode: 400,
      errorCode: 'mock_work_order_product_name_required',
    })
  }

  const shopIdentity = String(payload.sellerId || payload.shopId || '').trim()
  if (!shopIdentity) {
    throw createHttpError('请选择或输入店铺', {
      statusCode: 400,
      errorCode: 'mock_work_order_shop_required',
    })
  }
  const matchedShop =
    shops.find(
      (item) =>
        String(item.sellerId || item.shopId || '').trim() === shopIdentity ||
        String(item.shopId || '').trim() === shopIdentity,
    ) || null
  if (matchedShop?.enabled === false) {
    throw createHttpError('所选店铺已停用', {
      statusCode: 409,
      errorCode: 'mock_work_order_shop_disabled',
    })
  }
  // 未命中已配置店铺时视为自定义店铺（用于其他平台订单手动录入），
  // 与真实店铺一样落入 material.source，保证链路与展示一致。
  const isCustomShop = !matchedShop
  const shop =
    matchedShop ||
    ({
      enabled: true,
      sellerId: '',
      shopId: '',
      shopName: shopIdentity.slice(0, 64),
      customShopName: shopIdentity.slice(0, 64),
    } as KuaishouIndustryShopConfig)

  return {
    platformOrderId,
    productName,
    shop,
    isCustomShop,
    rewardAmount: requireMockWorkOrderAmount(payload.rewardAmount, '接单金额', 'reward_amount'),
    paymentAmount: requireMockWorkOrderAmount(
      payload.paymentAmount,
      '用户付款金额',
      'payment_amount',
    ),
  }
}

function requireMockWorkOrderAmount(value: unknown, label: string, field: string): number {
  if (value === undefined || value === null || String(value).trim() === '') {
    throw createHttpError(`请填写${label}`, {
      statusCode: 400,
      errorCode: `mock_work_order_${field}_required`,
    })
  }
  const amount = normalizeAmountFen(value, 0)
  if (amount <= 0) {
    throw createHttpError(`${label}必须大于 0`, {
      statusCode: 400,
      errorCode: `mock_work_order_${field}_invalid`,
    })
  }
  return amount
}
