/**
 * Multi-Payment Method System
 * Support for Chime, Cash App, PayPal, Google Pay, Bank Transfer, Check, Money Order
 */

export type PaymentMethod = 
  | 'square'
  | 'chime'
  | 'cashapp'
  | 'paypal'
  | 'google_pay'
  | 'bank_transfer'
  | 'check'
  | 'money_order';

export interface PaymentMethodConfig {
  id: PaymentMethod;
  name: string;
  displayName: string;
  icon: string;
  description: string;
  isActive: boolean;
  processingFee: number; // percentage
  minAmount: number; // SC
  maxAmount: number; // SC
  processingTime: string; // e.g., "Instant", "1-3 business days"
  supportedCountries: string[];
  requiresVerification: boolean;
  apiKey?: string;
  apiSecret?: string;
  webhookUrl?: string;
  settings: Record<string, any>;
}

export interface PaymentTransaction {
  id: string;
  userId: number;
  method: PaymentMethod;
  amount: number; // SC
  amountUSD: number;
  fee: number;
  status: 'pending' | 'processing' | 'completed' | 'failed' | 'refunded';
  transactionId: string;
  referenceId?: string;
  createdAt: Date;
  completedAt?: Date;
  failureReason?: string;
  metadata: Record<string, any>;
}

/**
 * Payment Method Configurations
 */
export const PAYMENT_METHODS: Record<PaymentMethod, PaymentMethodConfig> = {
  square: {
    id: 'square',
    name: 'Square',
    displayName: 'Credit/Debit Card',
    icon: '💳',
    description: 'Pay with credit or debit card',
    isActive: true,
    processingFee: 0.029, // 2.9%
    minAmount: 1,
    maxAmount: 10000,
    processingTime: 'Instant',
    supportedCountries: ['US', 'CA', 'AU', 'JP', 'GB', 'FR', 'DE'],
    requiresVerification: false,
    settings: {
      enableApplePay: true,
      enableGooglePay: true,
      enableACH: false,
    },
  },
  chime: {
    id: 'chime',
    name: 'Chime',
    displayName: 'Chime Bank Account',
    icon: '🏦',
    description: 'Pay directly from your Chime account',
    isActive: true,
    processingFee: 0.01, // 1%
    minAmount: 5,
    maxAmount: 5000,
    processingTime: '1-2 business days',
    supportedCountries: ['US'],
    requiresVerification: true,
    settings: {
      bankCode: 'CHIME',
      requiresPlaidVerification: true,
    },
  },
  cashapp: {
    id: 'cashapp',
    name: 'Cash App',
    displayName: 'Cash App',
    icon: '💵',
    description: 'Send money from your Cash App',
    isActive: true,
    processingFee: 0.015, // 1.5%
    minAmount: 1,
    maxAmount: 2500,
    processingTime: '1-3 business days',
    supportedCountries: ['US'],
    requiresVerification: false,
    settings: {
      cashtagRequired: true,
      manualVerification: true,
    },
  },
  paypal: {
    id: 'paypal',
    name: 'PayPal',
    displayName: 'PayPal',
    icon: '🅿️',
    description: 'Pay with your PayPal account',
    isActive: true,
    processingFee: 0.034, // 3.4%
    minAmount: 1,
    maxAmount: 10000,
    processingTime: 'Instant',
    supportedCountries: ['US', 'CA', 'AU', 'JP', 'GB', 'FR', 'DE', 'IT', 'ES'],
    requiresVerification: false,
    settings: {
      clientId: '',
      clientSecret: '',
      webhookId: '',
    },
  },
  google_pay: {
    id: 'google_pay',
    name: 'Google Pay',
    displayName: 'Google Pay',
    icon: '🔵',
    description: 'Pay with Google Pay',
    isActive: true,
    processingFee: 0.029, // 2.9%
    minAmount: 1,
    maxAmount: 10000,
    processingTime: 'Instant',
    supportedCountries: ['US', 'CA', 'AU', 'JP', 'GB', 'FR', 'DE'],
    requiresVerification: false,
    settings: {
      merchantId: '',
      merchantName: 'CoinKrazy',
    },
  },
  bank_transfer: {
    id: 'bank_transfer',
    name: 'Bank Transfer',
    displayName: 'Bank Transfer (ACH)',
    icon: '🏦',
    description: 'Transfer directly from your bank account',
    isActive: true,
    processingFee: 0.005, // 0.5%
    minAmount: 10,
    maxAmount: 25000,
    processingTime: '3-5 business days',
    supportedCountries: ['US'],
    requiresVerification: true,
    settings: {
      requiresPlaidVerification: true,
      dailyLimit: 10000,
      monthlyLimit: 50000,
    },
  },
  check: {
    id: 'check',
    name: 'Check',
    displayName: 'Check by Mail',
    icon: '✉️',
    description: 'Receive a check by mail',
    isActive: true,
    processingFee: 0, // No fee
    minAmount: 100,
    maxAmount: 50000,
    processingTime: '7-14 business days',
    supportedCountries: ['US'],
    requiresVerification: true,
    settings: {
      requiresAddressVerification: true,
      processingDays: 10,
    },
  },
  money_order: {
    id: 'money_order',
    name: 'Money Order',
    displayName: 'Money Order',
    icon: '💰',
    description: 'Receive a money order',
    isActive: true,
    processingFee: 0, // No fee
    minAmount: 50,
    maxAmount: 10000,
    processingTime: '5-10 business days',
    supportedCountries: ['US'],
    requiresVerification: true,
    settings: {
      requiresAddressVerification: true,
      processingDays: 7,
    },
  },
};

/**
 * Get active payment methods
 */
export function getActivePaymentMethods(): PaymentMethodConfig[] {
  return Object.values(PAYMENT_METHODS).filter(method => method.isActive);
}

/**
 * Get payment method by ID
 */
export function getPaymentMethod(id: PaymentMethod): PaymentMethodConfig | undefined {
  return PAYMENT_METHODS[id];
}

/**
 * Calculate processing fee
 */
export function calculateProcessingFee(
  method: PaymentMethod,
  amount: number
): number {
  const config = PAYMENT_METHODS[method];
  if (!config) return 0;
  return Math.round(amount * config.processingFee * 100) / 100;
}

/**
 * Validate payment amount
 */
export function validatePaymentAmount(
  method: PaymentMethod,
  amount: number
): { valid: boolean; reason?: string } {
  const config = PAYMENT_METHODS[method];
  if (!config) {
    return { valid: false, reason: 'Payment method not found' };
  }

  if (!config.isActive) {
    return { valid: false, reason: 'Payment method is currently unavailable' };
  }

  if (amount < config.minAmount) {
    return { valid: false, reason: `Minimum amount is ${config.minAmount} SC` };
  }

  if (amount > config.maxAmount) {
    return { valid: false, reason: `Maximum amount is ${config.maxAmount} SC` };
  }

  return { valid: true };
}

/**
 * Create payment transaction
 */
export function createPaymentTransaction(
  userId: number,
  method: PaymentMethod,
  amountSC: number,
  amountUSD: number
): Partial<PaymentTransaction> {
  const fee = calculateProcessingFee(method, amountSC);

  return {
    userId,
    method,
    amount: amountSC,
    amountUSD,
    fee,
    status: 'pending',
    transactionId: `TXN-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
    createdAt: new Date(),
    metadata: {},
  };
}

/**
 * Get payment method display info
 */
export function getPaymentMethodDisplay(method: PaymentMethod): {
  name: string;
  icon: string;
  displayName: string;
} {
  const config = PAYMENT_METHODS[method];
  return {
    name: config?.name || method,
    icon: config?.icon || '💳',
    displayName: config?.displayName || method,
  };
}

/**
 * Get processing time for method
 */
export function getProcessingTime(method: PaymentMethod): string {
  const config = PAYMENT_METHODS[method];
  return config?.processingTime || 'Unknown';
}

/**
 * Check if method requires verification
 */
export function requiresVerification(method: PaymentMethod): boolean {
  const config = PAYMENT_METHODS[method];
  return config?.requiresVerification || false;
}

/**
 * Get supported countries for method
 */
export function getSupportedCountries(method: PaymentMethod): string[] {
  const config = PAYMENT_METHODS[method];
  return config?.supportedCountries || [];
}

/**
 * Update payment method config
 */
export function updatePaymentMethodConfig(
  method: PaymentMethod,
  updates: Partial<PaymentMethodConfig>
): PaymentMethodConfig {
  const config = PAYMENT_METHODS[method];
  if (!config) throw new Error(`Payment method ${method} not found`);

  return {
    ...config,
    ...updates,
  };
}

/**
 * Generate payment receipt
 */
export function generatePaymentReceipt(transaction: PaymentTransaction): string {
  const method = getPaymentMethodDisplay(transaction.method);
  const date = new Date(transaction.createdAt).toLocaleDateString();
  const time = new Date(transaction.createdAt).toLocaleTimeString();

  return `
COINKRAZY PAYMENT RECEIPT
========================

Transaction ID: ${transaction.transactionId}
Date: ${date} ${time}
Status: ${transaction.status.toUpperCase()}

Payment Method: ${method.displayName}
Amount: ${transaction.amount} SC
USD Value: $${transaction.amountUSD.toFixed(2)}
Processing Fee: $${transaction.fee.toFixed(2)}

${transaction.referenceId ? `Reference ID: ${transaction.referenceId}` : ''}
${transaction.failureReason ? `Failure Reason: ${transaction.failureReason}` : ''}

Thank you for your purchase!
  `;
}

/**
 * Get payment method categories
 */
export const PAYMENT_CATEGORIES = {
  digital: ['square', 'paypal', 'google_pay', 'cashapp'],
  bank: ['chime', 'bank_transfer'],
  traditional: ['check', 'money_order'],
};

/**
 * Get methods by category
 */
export function getMethodsByCategory(category: keyof typeof PAYMENT_CATEGORIES): PaymentMethodConfig[] {
  const methodIds = PAYMENT_CATEGORIES[category];
  return methodIds
    .map(id => PAYMENT_METHODS[id as PaymentMethod])
    .filter(method => method && method.isActive);
}
