/** 转账单对账/补单动作是否可用（与后台 API can_* 字段对齐）。 */

export type TransferOrderActionRow = {
  direction?: string;
  status: string;
  fail_reason?: string | null;
  external_ref_no?: string | null;
  can_reverse?: boolean;
  can_complete_credit?: boolean;
  can_manually_process?: boolean;
};

export function canReverseTransferOrder(row: TransferOrderActionRow, canWriteWallet: boolean): boolean {
  return canWriteWallet && row.can_reverse === true;
}

export function canCompleteTransferInCredit(row: TransferOrderActionRow, canWriteWallet: boolean): boolean {
  return (
    canWriteWallet &&
    (row.can_complete_credit ??
      (row.direction === "in" &&
        row.status === "pending_reconcile" &&
        row.fail_reason === "lottery_credit_failed" &&
        Boolean(row.external_ref_no?.trim())))
  );
}

export function canManuallyProcessTransferOrder(row: TransferOrderActionRow, canWriteWallet: boolean): boolean {
  return (
    canWriteWallet &&
    (row.can_manually_process ??
      (["processing", "failed", "pending_reconcile"].includes(row.status) &&
        !(row.direction === "out" && row.status === "pending_reconcile") &&
        row.fail_reason !== "lottery_credit_failed"))
  );
}

export function transferOrderHasReconcileAction(row: TransferOrderActionRow, canWriteWallet: boolean): boolean {
  return (
    canReverseTransferOrder(row, canWriteWallet) ||
    canCompleteTransferInCredit(row, canWriteWallet) ||
    canManuallyProcessTransferOrder(row, canWriteWallet)
  );
}
