/**
 * Affiliate Signup Flow System
 * Application form, KYC verification, and approval workflow
 */

export interface AffiliateApplication {
  id: number;
  userId: number;
  status: 'pending' | 'approved' | 'rejected' | 'under_review';
  applicationDate: Date;
  approvalDate?: Date;
  rejectionReason?: string;
  kycStatus: 'pending' | 'verified' | 'rejected';
  bankDetails?: {
    accountHolder: string;
    accountNumber: string;
    bankName: string;
    routingNumber?: string;
  };
  paypalEmail?: string;
  cryptoWallet?: string;
}

export interface AffiliateApplicationForm {
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  website?: string;
  promotionChannels: string[]; // email, social, content, etc.
  estimatedMonthlyReferrals: number;
  paymentMethod: 'bank_transfer' | 'paypal' | 'crypto';
  paymentDetails: Record<string, string>;
  agreeToTerms: boolean;
  agreeToPrivacy: boolean;
}

export interface KYCVerification {
  id: number;
  affiliateId: number;
  status: 'pending' | 'verified' | 'rejected';
  documentType: 'passport' | 'drivers_license' | 'national_id';
  documentUrl: string;
  verificationDate?: Date;
  rejectionReason?: string;
}

/**
 * Validate affiliate application
 */
export function validateAffiliateApplication(form: AffiliateApplicationForm): {
  valid: boolean;
  errors: string[];
} {
  const errors: string[] = [];

  if (!form.firstName || form.firstName.trim().length < 2) {
    errors.push('First name must be at least 2 characters');
  }

  if (!form.lastName || form.lastName.trim().length < 2) {
    errors.push('Last name must be at least 2 characters');
  }

  if (!form.email || !form.email.includes('@')) {
    errors.push('Valid email address required');
  }

  if (!form.phone || form.phone.length < 10) {
    errors.push('Valid phone number required');
  }

  if (form.promotionChannels.length === 0) {
    errors.push('Select at least one promotion channel');
  }

  if (form.estimatedMonthlyReferrals < 1) {
    errors.push('Estimated monthly referrals must be at least 1');
  }

  if (!form.agreeToTerms) {
    errors.push('You must agree to the terms and conditions');
  }

  if (!form.agreeToPrivacy) {
    errors.push('You must agree to the privacy policy');
  }

  return {
    valid: errors.length === 0,
    errors,
  };
}

/**
 * Validate payment details
 */
export function validatePaymentDetails(
  method: string,
  details: Record<string, string>
): { valid: boolean; reason?: string } {
  switch (method) {
    case 'bank_transfer':
      if (!details.accountHolder || !details.accountNumber || !details.bankName) {
        return { valid: false, reason: 'All bank details are required' };
      }
      if (details.accountNumber.length < 8) {
        return { valid: false, reason: 'Invalid account number' };
      }
      break;

    case 'paypal':
      if (!details.email || !details.email.includes('@')) {
        return { valid: false, reason: 'Valid PayPal email required' };
      }
      break;

    case 'crypto':
      if (!details.walletAddress) {
        return { valid: false, reason: 'Wallet address required' };
      }
      if (details.walletAddress.length < 26) {
        return { valid: false, reason: 'Invalid wallet address' };
      }
      break;
  }

  return { valid: true };
}

/**
 * Create affiliate application
 */
export function createAffiliateApplication(
  userId: number,
  form: AffiliateApplicationForm
): Partial<AffiliateApplication> {
  return {
    userId,
    status: 'pending',
    applicationDate: new Date(),
    kycStatus: 'pending',
  };
}

/**
 * Calculate approval score
 */
export function calculateApprovalScore(form: AffiliateApplicationForm): number {
  let score = 0;

  // Website presence
  if (form.website) score += 20;

  // Multiple promotion channels
  if (form.promotionChannels.length >= 3) score += 20;
  else if (form.promotionChannels.length >= 2) score += 10;

  // Estimated referrals
  if (form.estimatedMonthlyReferrals >= 100) score += 30;
  else if (form.estimatedMonthlyReferrals >= 50) score += 20;
  else if (form.estimatedMonthlyReferrals >= 10) score += 10;

  // Payment method (crypto is lower risk)
  if (form.paymentMethod === 'crypto') score += 10;
  else if (form.paymentMethod === 'paypal') score += 5;

  return Math.min(100, score);
}

/**
 * Get approval recommendation
 */
export function getApprovalRecommendation(score: number): {
  recommendation: 'auto_approve' | 'manual_review' | 'reject';
  reason: string;
} {
  if (score >= 70) {
    return {
      recommendation: 'auto_approve',
      reason: 'High-quality affiliate application with strong indicators',
    };
  }

  if (score >= 40) {
    return {
      recommendation: 'manual_review',
      reason: 'Application meets basic requirements, manual review recommended',
    };
  }

  return {
    recommendation: 'reject',
    reason: 'Application does not meet minimum requirements',
  };
}

/**
 * Generate approval email
 */
export function generateApprovalEmail(
  affiliateName: string,
  affiliateCode: string
): { subject: string; htmlContent: string } {
  return {
    subject: 'Welcome to CoinKrazy Affiliate Program! 🎉',
    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; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 8px; }
    .content { padding: 20px 0; }
    .cta-button { display: inline-block; background-color: #667eea; color: white; padding: 12px 30px; text-decoration: none; border-radius: 4px; margin: 20px 0; }
    .code-box { background-color: #f0f4ff; border-left: 4px solid #667eea; padding: 15px; margin: 20px 0; font-family: monospace; font-size: 18px; font-weight: bold; }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>Welcome, ${affiliateName}! 🎉</h1>
      <p>Your affiliate application has been approved!</p>
    </div>
    
    <div class="content">
      <p>Congratulations! Your application to join the CoinKrazy Affiliate Program has been approved.</p>
      
      <p>You're now ready to start earning commissions by promoting CoinKrazy!</p>
      
      <h3>Your Affiliate Code</h3>
      <div class="code-box">
        ${affiliateCode}
      </div>
      
      <h3>Next Steps</h3>
      <ol>
        <li>Log in to your affiliate dashboard</li>
        <li>Complete the onboarding tutorial (optional but recommended)</li>
        <li>Download marketing materials</li>
        <li>Start promoting CoinKrazy</li>
        <li>Track your earnings in real-time</li>
      </ol>
      
      <center>
        <a href="https://coinkrazy.com/affiliate/dashboard" class="cta-button">Go to Dashboard</a>
      </center>
      
      <h3>Key Benefits</h3>
      <ul>
        <li>✓ Earn 5-20% commission on referrals</li>
        <li>✓ Monthly bonuses up to 1000 SC</li>
        <li>✓ Daily payouts for top affiliates</li>
        <li>✓ Professional marketing materials</li>
        <li>✓ Dedicated support team</li>
      </ul>
      
      <p>If you have any questions, don't hesitate to reach out to our affiliate support team at affiliates@coinkrazy.com</p>
      
      <p>Good luck and happy promoting! 🚀</p>
    </div>
  </div>
</body>
</html>
    `,
  };
}

/**
 * Generate rejection email
 */
export function generateRejectionEmail(
  affiliateName: string,
  reason: string
): { subject: string; htmlContent: string } {
  return {
    subject: 'CoinKrazy Affiliate Application Status',
    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; background-color: #f0f0f0; border-radius: 8px; }
    .content { padding: 20px 0; }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h2>Application Status Update</h2>
    </div>
    
    <div class="content">
      <p>Hi ${affiliateName},</p>
      
      <p>Thank you for your interest in the CoinKrazy Affiliate Program.</p>
      
      <p>Unfortunately, your application was not approved at this time. Reason: ${reason}</p>
      
      <h3>What You Can Do</h3>
      <ul>
        <li>Reapply after 30 days with updated information</li>
        <li>Contact our support team for feedback: affiliates@coinkrazy.com</li>
        <li>Continue playing CoinKrazy and use your referral link as a regular player</li>
      </ul>
      
      <p>We appreciate your interest and hope to work with you in the future!</p>
    </div>
  </div>
</body>
</html>
    `,
  };
}

/**
 * Promotion channel options
 */
export const PROMOTION_CHANNELS = [
  { id: 'email', name: 'Email Marketing', description: 'Email lists and newsletters' },
  { id: 'social', name: 'Social Media', description: 'Facebook, Twitter, Instagram, TikTok' },
  { id: 'content', name: 'Content Marketing', description: 'Blog, YouTube, Medium' },
  { id: 'forum', name: 'Forum & Communities', description: 'Reddit, Discord, forums' },
  { id: 'paid_ads', name: 'Paid Advertising', description: 'Google Ads, Facebook Ads' },
  { id: 'website', name: 'Website', description: 'Your own website or blog' },
];

/**
 * Get promotion channel name
 */
export function getPromotionChannelName(channelId: string): string {
  const channel = PROMOTION_CHANNELS.find(c => c.id === channelId);
  return channel?.name || channelId;
}
