import type { TaskUpdatePatch } from '../../../types/repository/inputs.js'
import type { TaskRow } from '../../../types/repository/rows.js'

export const FULFILLMENT_EXECUTOR_KEYS = {
  MANUAL_DISPATCH: 'manual_dispatch',
  KUAISHOU_CLOUD: 'kuaishou_ct_assisted',
  KUAISHOU_INDUSTRY: 'kuaishou-industry',
  KUAISHOU_FEIFEI: 'kuaishou_feifei',
  AFFILIATE_DASH: 'affiliate_dash',
} as const

export type FulfillmentExecutorKey =
  | (typeof FULFILLMENT_EXECUTOR_KEYS)[keyof typeof FULFILLMENT_EXECUTOR_KEYS]
  | (string & {})

export type FulfillmentDeliveryLink = {
  claimUrl: string
  expireTime?: unknown
}

export type FulfillmentPrepareDeps = {
  updateTask: (taskId: number | string, patch: TaskUpdatePatch) => Promise<TaskRow | null>
  createTaskClaimToken: (taskId: number | string) => Promise<{
    token: string
    expired_at: string | null
    [key: string]: unknown
  }>
  notifyTaskAutoManualReview: (payload: {
    task: unknown
    reason: string
    source: string
  }) => Promise<unknown> | unknown
  nowIso: () => string
}

export type FulfillmentActionOptions = {
  source?: string
  actor?: unknown
  autoFinalize?: boolean
  errorCodePrefix?: string
  /**
   * 退号时是否顺带核销行业电子凭证。
   * - true/默认：发货收尾（claim autoFinalize）
   * - false：仅清理虚拟号（admin 退号），与核销无关
   */
  consumeIndustryVoucher?: boolean
  [key: string]: unknown
}

export type FulfillmentActionResult = {
  task: TaskRow
  [key: string]: unknown
}

export type FulfillmentExecutor = {
  key: FulfillmentExecutorKey
  preparePaidTask?: (task: TaskRow, deps: FulfillmentPrepareDeps) => Promise<TaskRow | null>
  resolveDeliveryLink?: (task: TaskRow) => Promise<FulfillmentDeliveryLink | null>
  /** lewan：准备绑定资源（虚拟号 / bindUrl） */
  prepareBinding?: (
    task: TaskRow,
    options?: FulfillmentActionOptions,
  ) => Promise<FulfillmentActionResult>
  /** lewan：换绑角色 */
  rebindRole?: (
    task: TaskRow,
    options?: FulfillmentActionOptions,
  ) => Promise<FulfillmentActionResult>
  /** lewan：刷新角色信息 */
  refreshRole?: (
    task: TaskRow,
    options?: FulfillmentActionOptions,
  ) => Promise<FulfillmentActionResult>
  /** lewan：确认角色（UID 匹配后落 ROLE_CONFIRMED） */
  confirmRole?: (
    task: TaskRow,
    options?: FulfillmentActionOptions,
  ) => Promise<FulfillmentActionResult>
  /** lewan：一键兑换（状态机 + dispatch） */
  redeemTask?: (
    task: TaskRow,
    options?: FulfillmentActionOptions,
  ) => Promise<FulfillmentActionResult>
  /** lewan：后台/系统发货（不经 claim 一键兑换） */
  dispatchTask?: (
    task: TaskRow,
    options?: FulfillmentActionOptions,
  ) => Promise<FulfillmentActionResult>
  /**
   * lewan：退还虚拟号。
   * 默认可顺带核销；admin 清理请传 consumeIndustryVoucher: false。
   */
  returnNumber?: (
    task: TaskRow,
    options?: FulfillmentActionOptions,
  ) => Promise<FulfillmentActionResult>
}

export function normalizeExecutorKey(value: unknown): FulfillmentExecutorKey {
  return String(value || '').trim() as FulfillmentExecutorKey
}

export function isKuaishouCloudExecutor(value: unknown): boolean {
  const executorKey = normalizeExecutorKey(value)
  return (
    executorKey === FULFILLMENT_EXECUTOR_KEYS.KUAISHOU_CLOUD ||
    executorKey === FULFILLMENT_EXECUTOR_KEYS.KUAISHOU_INDUSTRY
  )
}

export function isKuaishouFeifeiExecutor(value: unknown): boolean {
  return normalizeExecutorKey(value) === FULFILLMENT_EXECUTOR_KEYS.KUAISHOU_FEIFEI
}

export function isAffiliateDashExecutor(value: unknown): boolean {
  return normalizeExecutorKey(value) === FULFILLMENT_EXECUTOR_KEYS.AFFILIATE_DASH
}

export function isManualDispatchExecutor(value: unknown): boolean {
  return normalizeExecutorKey(value) === FULFILLMENT_EXECUTOR_KEYS.MANUAL_DISPATCH
}
