import { listKuaishouIndustryVouchersByOid } from '../../repositories/kuaishou-industry-voucher-repo.js'
import { bindKuaishouIndustryVouchersToOrderTasks } from '../platforms/kuaishou-industry/voucher-binding-service.js'
import {
  isKuaishouIndustryVoucherSendCallbackSuccess,
  resolveKuaishouIndustryVoucherSendCallbackMessage,
} from '../platforms/kuaishou-industry/voucher-service.js'
import type { KuaishouIndustryVoucherRow, OrderRow, TaskRow } from '../../types/repository/rows.js'

export const ORDER_FULFILLMENT_BLOCK_REASONS = {
  KUAISHOU_INDUSTRY_SEND_CALLBACK_UNCONFIRMED: 'kuaishou_industry_send_callback_unconfirmed',
} as const

type FulfillmentReadinessDeps = {
  listKuaishouIndustryVouchersByOid?: typeof listKuaishouIndustryVouchersByOid
}

export async function resolveOrderFulfillmentReadiness(
  order: Pick<OrderRow, 'platform_order_id'> | null | undefined,
  deps: FulfillmentReadinessDeps = {},
) {
  const listVouchers = deps.listKuaishouIndustryVouchersByOid || listKuaishouIndustryVouchersByOid
  const oid = String(order?.platform_order_id || '').trim()
  if (!oid) {
    return {
      allowed: true,
      voucherCount: 0,
      reason: '',
      blockReason: '',
    }
  }

  const vouchers = await listVouchers(oid)
  if (vouchers.length === 0 || vouchers.every(isKuaishouIndustryVoucherSendCallbackSuccess)) {
    return {
      allowed: true,
      voucherCount: vouchers.length,
      reason: '',
      blockReason: '',
    }
  }

  const blockedVoucher = vouchers.find(
    (voucher) => !isKuaishouIndustryVoucherSendCallbackSuccess(voucher),
  )

  return {
    allowed: false,
    voucherCount: vouchers.length,
    reason: blockedVoucher
      ? resolveKuaishouIndustryVoucherSendCallbackMessage(blockedVoucher)
      : '电子凭证发码回调未确认',
    blockReason: ORDER_FULFILLMENT_BLOCK_REASONS.KUAISHOU_INDUSTRY_SEND_CALLBACK_UNCONFIRMED,
  }
}

export async function syncOrderFulfillmentAttachments(
  order: OrderRow,
  tasks: TaskRow[] = [],
  options: {
    source?: string
    now?: string
  } = {},
): Promise<KuaishouIndustryVoucherRow[]> {
  return bindKuaishouIndustryVouchersToOrderTasks(order, tasks, options)
}
