/**
 * Affiliate Payouts System
 * Automated payout processing and payment management
 */

export interface AffiliatePayoutRequest {
  id: number;
  affiliateId: number;
  amount: number; // SC amount
  status: 'pending' | 'processing' | 'completed' | 'failed' | 'cancelled';
  paymentMethod: 'bank_transfer' | 'paypal' | 'crypto' | 'store_credit';
  requestedAt: Date;
  processedAt?: Date;
  completedAt?: Date;
  failureReason?: string;
}

export interface PayoutSchedule {
  tier: 'bronze' | 'silver' | 'gold' | 'platinum' | 'diamond';
  frequency: 'monthly' | 'bi-weekly' | 'weekly' | 'daily';
  nextPayoutDate: Date;
  minimumAmount: number; // SC
}

export interface PayoutBatch {
  id: number;
  batchDate: Date;
  tier: string;
  totalAmount: number;
  payoutCount: number;
  status: 'pending' | 'processing' | 'completed' | 'failed';
  createdAt: Date;
  completedAt?: Date;
}

export interface PaymentMethod {
  id: number;
  affiliateId: number;
  type: 'bank_transfer' | 'paypal' | 'crypto' | 'store_credit';
  details: Record<string, string>; // encrypted
  isDefault: boolean;
  verified: boolean;
  createdAt: Date;
}

/**
 * Payout Schedule Configuration
 */
export const PAYOUT_SCHEDULES: Record<string, PayoutSchedule> = {
  bronze: {
    tier: 'bronze',
    frequency: 'monthly',
    nextPayoutDate: new Date(),
    minimumAmount: 100,
  },
  silver: {
    tier: 'silver',
    frequency: 'weekly',
    nextPayoutDate: new Date(),
    minimumAmount: 100,
  },
  gold: {
    tier: 'gold',
    frequency: 'bi-weekly',
    nextPayoutDate: new Date(),
    minimumAmount: 100,
  },
  platinum: {
    tier: 'platinum',
    frequency: 'weekly',
    nextPayoutDate: new Date(),
    minimumAmount: 100,
  },
  diamond: {
    tier: 'diamond',
    frequency: 'daily',
    nextPayoutDate: new Date(),
    minimumAmount: 100,
  },
};

/**
 * Calculate next payout date
 */
export function calculateNextPayoutDate(frequency: string): Date {
  const now = new Date();
  const nextDate = new Date(now);

  switch (frequency) {
    case 'daily':
      nextDate.setDate(nextDate.getDate() + 1);
      break;
    case 'weekly':
      nextDate.setDate(nextDate.getDate() + 7);
      break;
    case 'bi-weekly':
      nextDate.setDate(nextDate.getDate() + 14);
      break;
    case 'monthly':
      nextDate.setMonth(nextDate.getMonth() + 1);
      break;
  }

  return nextDate;
}

/**
 * Validate payout request
 */
export function validatePayoutRequest(
  amount: number,
  minimumAmount: number,
  balance: number
): { valid: boolean; reason?: string } {
  if (amount < minimumAmount) {
    return { valid: false, reason: `Minimum payout amount is ${minimumAmount} SC` };
  }

  if (amount > balance) {
    return { valid: false, reason: 'Insufficient balance for payout' };
  }

  if (amount <= 0) {
    return { valid: false, reason: 'Payout amount must be greater than 0' };
  }

  return { valid: true };
}

/**
 * Calculate payout fees
 */
export function calculatePayoutFees(
  amount: number,
  paymentMethod: string
): { amount: number; fee: number; total: number } {
  let feePercentage = 0;

  switch (paymentMethod) {
    case 'bank_transfer':
      feePercentage = 0.02; // 2%
      break;
    case 'paypal':
      feePercentage = 0.03; // 3%
      break;
    case 'crypto':
      feePercentage = 0.01; // 1%
      break;
    case 'store_credit':
      feePercentage = 0; // No fee
      break;
  }

  const fee = Math.round(amount * feePercentage * 100) / 100;
  const total = amount + fee;

  return { amount, fee, total };
}

/**
 * Create payout request
 */
export function createPayoutRequest(
  affiliateId: number,
  amount: number,
  paymentMethod: string
): Partial<AffiliatePayoutRequest> {
  return {
    affiliateId,
    amount,
    paymentMethod: paymentMethod as any,
    status: 'pending',
    requestedAt: new Date(),
  };
}

/**
 * Process payout batch
 */
export function processBatch(
  tier: string,
  payouts: AffiliatePayoutRequest[]
): PayoutBatch {
  const totalAmount = payouts.reduce((sum, payout) => sum + payout.amount, 0);

  return {
    id: Math.floor(Math.random() * 1000000),
    batchDate: new Date(),
    tier,
    totalAmount,
    payoutCount: payouts.length,
    status: 'processing',
    createdAt: new Date(),
  };
}

/**
 * Get payout schedule for tier
 */
export function getPayoutSchedule(tier: string): PayoutSchedule | undefined {
  return PAYOUT_SCHEDULES[tier];
}

/**
 * Calculate payout frequency in days
 */
export function getPayoutFrequencyDays(frequency: string): number {
  const frequencies: Record<string, number> = {
    daily: 1,
    weekly: 7,
    'bi-weekly': 14,
    monthly: 30,
  };
  return frequencies[frequency] || 30;
}

/**
 * Get pending payouts for affiliate
 */
export function getPendingPayouts(payouts: AffiliatePayoutRequest[]): AffiliatePayoutRequest[] {
  return payouts.filter(payout => payout.status === 'pending');
}

/**
 * Get completed payouts for affiliate
 */
export function getCompletedPayouts(payouts: AffiliatePayoutRequest[]): AffiliatePayoutRequest[] {
  return payouts.filter(payout => payout.status === 'completed');
}

/**
 * Calculate total earnings from payouts
 */
export function calculateTotalEarnings(payouts: AffiliatePayoutRequest[]): number {
  return payouts
    .filter(payout => payout.status === 'completed')
    .reduce((sum, payout) => sum + payout.amount, 0);
}

/**
 * Generate payout confirmation email
 */
export function generatePayoutConfirmationEmail(
  affiliateName: string,
  amount: number,
  paymentMethod: string,
  estimatedDate: Date
): { subject: string; htmlContent: string } {
  return {
    subject: `Payout Confirmation: ${amount} SC`,
    htmlContent: `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <style>
    body { font-family: Arial, sans-serif; background-color: #f5f5f5; }
    .container { max-width: 600px; margin: 0 auto; background-color: white; padding: 20px; border-radius: 8px; }
    .header { text-align: center; padding: 20px 0; border-bottom: 2px solid #28a745; }
    .success-badge { display: inline-block; background-color: #28a745; color: white; padding: 8px 16px; border-radius: 20px; }
    .details { background-color: #f0f0f0; padding: 15px; border-radius: 4px; margin: 20px 0; }
    .detail-row { display: flex; justify-content: space-between; padding: 8px 0; }
    .label { font-weight: bold; }
    .footer { text-align: center; padding: 20px 0; border-top: 1px solid #e0e0e0; color: #666; font-size: 12px; }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <div class="success-badge">✓ Payout Confirmed</div>
      <h2>Payout Processed Successfully</h2>
    </div>
    
    <div>
      <p>Hi ${affiliateName},</p>
      
      <p>Your payout request has been processed successfully! 🎉</p>
      
      <div class="details">
        <div class="detail-row">
          <span class="label">Amount:</span>
          <span>${amount} SC</span>
        </div>
        <div class="detail-row">
          <span class="label">Payment Method:</span>
          <span>${paymentMethod}</span>
        </div>
        <div class="detail-row">
          <span class="label">Estimated Arrival:</span>
          <span>${estimatedDate.toLocaleDateString()}</span>
        </div>
      </div>
      
      <p>Your funds should arrive within 1-3 business days depending on your payment method.</p>
      
      <p>Thank you for being an amazing CoinKrazy affiliate! Keep up the great work! 🚀</p>
      
      <p>If you have any questions, feel free to reach out to our support team.</p>
    </div>
    
    <div class="footer">
      <p>© 2026 CoinKrazy. All rights reserved.</p>
    </div>
  </div>
</body>
</html>
    `,
  };
}

/**
 * Check if affiliate is eligible for payout
 */
export function checkPayoutEligibility(
  balance: number,
  minimumAmount: number,
  kycVerified: boolean
): { eligible: boolean; reason?: string } {
  if (!kycVerified) {
    return { eligible: false, reason: 'KYC verification required for payouts' };
  }

  if (balance < minimumAmount) {
    return { eligible: false, reason: `Minimum balance of ${minimumAmount} SC required` };
  }

  return { eligible: true };
}
