/**
 * Email Notification Service
 * Sends email notifications via Brevo for payment events
 */

export type EmailNotificationType =
  | 'withdrawal_requested'
  | 'withdrawal_approved'
  | 'withdrawal_rejected'
  | 'withdrawal_completed'
  | 'withdrawal_failed'
  | 'payment_received'
  | 'fraud_alert'
  | 'high_value_transaction'
  | 'refund_processed';

export interface EmailTemplate {
  type: EmailNotificationType;
  subject: string;
  htmlTemplate: string;
  textTemplate: string;
}

export interface EmailNotification {
  id: string;
  type: EmailNotificationType;
  recipientEmail: string;
  recipientName: string;
  subject: string;
  htmlContent: string;
  textContent: string;
  data: Record<string, any>;
  status: 'pending' | 'sent' | 'failed' | 'bounced';
  sentAt?: Date;
  failureReason?: string;
  retryCount: number;
  maxRetries: number;
}

/**
 * Email templates
 */
export const EMAIL_TEMPLATES: Record<EmailNotificationType, EmailTemplate> = {
  withdrawal_requested: {
    type: 'withdrawal_requested',
    subject: 'Withdrawal Request Received',
    htmlTemplate: `
      <h2>Withdrawal Request Received</h2>
      <p>Hello {{playerName}},</p>
      <p>We have received your withdrawal request for {{amount}} {{currency}}.</p>
      <p><strong>Request Details:</strong></p>
      <ul>
        <li>Amount: {{amount}} {{currency}}</li>
        <li>Method: {{method}}</li>
        <li>Request ID: {{withdrawalId}}</li>
        <li>Status: Pending Review</li>
      </ul>
      <p>We will review your request and notify you of the status within 24 hours.</p>
      <p>Best regards,<br/>CoinKrazy Team</p>
    `,
    textTemplate: `
      Withdrawal Request Received
      
      Hello {{playerName}},
      
      We have received your withdrawal request for {{amount}} {{currency}}.
      
      Request Details:
      - Amount: {{amount}} {{currency}}
      - Method: {{method}}
      - Request ID: {{withdrawalId}}
      - Status: Pending Review
      
      We will review your request and notify you of the status within 24 hours.
      
      Best regards,
      CoinKrazy Team
    `,
  },
  withdrawal_approved: {
    type: 'withdrawal_approved',
    subject: 'Withdrawal Request Approved',
    htmlTemplate: `
      <h2>Withdrawal Request Approved</h2>
      <p>Hello {{playerName}},</p>
      <p>Great news! Your withdrawal request has been approved.</p>
      <p><strong>Approval Details:</strong></p>
      <ul>
        <li>Amount: {{amount}} {{currency}}</li>
        <li>Method: {{method}}</li>
        <li>Request ID: {{withdrawalId}}</li>
        <li>Status: Approved</li>
        <li>Processing Time: 1-3 business days</li>
      </ul>
      <p>Your funds will be transferred to your {{method}} account shortly.</p>
      <p>Best regards,<br/>CoinKrazy Team</p>
    `,
    textTemplate: `
      Withdrawal Request Approved
      
      Hello {{playerName}},
      
      Great news! Your withdrawal request has been approved.
      
      Approval Details:
      - Amount: {{amount}} {{currency}}
      - Method: {{method}}
      - Request ID: {{withdrawalId}}
      - Status: Approved
      - Processing Time: 1-3 business days
      
      Your funds will be transferred to your {{method}} account shortly.
      
      Best regards,
      CoinKrazy Team
    `,
  },
  withdrawal_rejected: {
    type: 'withdrawal_rejected',
    subject: 'Withdrawal Request Rejected',
    htmlTemplate: `
      <h2>Withdrawal Request Rejected</h2>
      <p>Hello {{playerName}},</p>
      <p>Unfortunately, your withdrawal request has been rejected.</p>
      <p><strong>Rejection Details:</strong></p>
      <ul>
        <li>Amount: {{amount}} {{currency}}</li>
        <li>Request ID: {{withdrawalId}}</li>
        <li>Reason: {{reason}}</li>
      </ul>
      <p>Your funds remain in your account. Please contact support if you have questions.</p>
      <p>Best regards,<br/>CoinKrazy Team</p>
    `,
    textTemplate: `
      Withdrawal Request Rejected
      
      Hello {{playerName}},
      
      Unfortunately, your withdrawal request has been rejected.
      
      Rejection Details:
      - Amount: {{amount}} {{currency}}
      - Request ID: {{withdrawalId}}
      - Reason: {{reason}}
      
      Your funds remain in your account. Please contact support if you have questions.
      
      Best regards,
      CoinKrazy Team
    `,
  },
  withdrawal_completed: {
    type: 'withdrawal_completed',
    subject: 'Withdrawal Completed',
    htmlTemplate: `
      <h2>Withdrawal Completed</h2>
      <p>Hello {{playerName}},</p>
      <p>Your withdrawal has been successfully processed!</p>
      <p><strong>Completion Details:</strong></p>
      <ul>
        <li>Amount: {{amount}} {{currency}}</li>
        <li>Method: {{method}}</li>
        <li>Request ID: {{withdrawalId}}</li>
        <li>Payout ID: {{payoutId}}</li>
        <li>Completed: {{completedDate}}</li>
      </ul>
      <p>The funds should appear in your account within 1-3 business days.</p>
      <p>Best regards,<br/>CoinKrazy Team</p>
    `,
    textTemplate: `
      Withdrawal Completed
      
      Hello {{playerName}},
      
      Your withdrawal has been successfully processed!
      
      Completion Details:
      - Amount: {{amount}} {{currency}}
      - Method: {{method}}
      - Request ID: {{withdrawalId}}
      - Payout ID: {{payoutId}}
      - Completed: {{completedDate}}
      
      The funds should appear in your account within 1-3 business days.
      
      Best regards,
      CoinKrazy Team
    `,
  },
  withdrawal_failed: {
    type: 'withdrawal_failed',
    subject: 'Withdrawal Processing Failed',
    htmlTemplate: `
      <h2>Withdrawal Processing Failed</h2>
      <p>Hello {{playerName}},</p>
      <p>We encountered an error processing your withdrawal.</p>
      <p><strong>Failure Details:</strong></p>
      <ul>
        <li>Amount: {{amount}} {{currency}}</li>
        <li>Request ID: {{withdrawalId}}</li>
        <li>Reason: {{reason}}</li>
      </ul>
      <p>Your funds have been returned to your account. Please try again or contact support.</p>
      <p>Best regards,<br/>CoinKrazy Team</p>
    `,
    textTemplate: `
      Withdrawal Processing Failed
      
      Hello {{playerName}},
      
      We encountered an error processing your withdrawal.
      
      Failure Details:
      - Amount: {{amount}} {{currency}}
      - Request ID: {{withdrawalId}}
      - Reason: {{reason}}
      
      Your funds have been returned to your account. Please try again or contact support.
      
      Best regards,
      CoinKrazy Team
    `,
  },
  payment_received: {
    type: 'payment_received',
    subject: 'Payment Received - Coins Added',
    htmlTemplate: `
      <h2>Payment Received</h2>
      <p>Hello {{playerName}},</p>
      <p>Thank you for your purchase! Your coins have been added to your account.</p>
      <p><strong>Purchase Details:</strong></p>
      <ul>
        <li>Amount: ${{amount}}</li>
        <li>Gold Coins: {{gcAmount}}</li>
        <li>Bonus Sweep Coins: {{scBonus}}</li>
        <li>Transaction ID: {{transactionId}}</li>
      </ul>
      <p>You can now use your coins to play our casino games!</p>
      <p>Best regards,<br/>CoinKrazy Team</p>
    `,
    textTemplate: `
      Payment Received
      
      Hello {{playerName}},
      
      Thank you for your purchase! Your coins have been added to your account.
      
      Purchase Details:
      - Amount: ${{amount}}
      - Gold Coins: {{gcAmount}}
      - Bonus Sweep Coins: {{scBonus}}
      - Transaction ID: {{transactionId}}
      
      You can now use your coins to play our casino games!
      
      Best regards,
      CoinKrazy Team
    `,
  },
  fraud_alert: {
    type: 'fraud_alert',
    subject: '[ADMIN] Fraud Alert - High Risk Transaction',
    htmlTemplate: `
      <h2>Fraud Alert</h2>
      <p>A high-risk transaction has been detected.</p>
      <p><strong>Transaction Details:</strong></p>
      <ul>
        <li>Player: {{playerName}} (ID: {{playerId}})</li>
        <li>Amount: ${{amount}}</li>
        <li>Risk Level: {{riskLevel}}</li>
        <li>Transaction ID: {{transactionId}}</li>
        <li>Indicators: {{indicators}}</li>
      </ul>
      <p><strong>Action Required:</strong> Please review this transaction immediately.</p>
      <p><a href="{{dashboardUrl}}">View in Dashboard</a></p>
    `,
    textTemplate: `
      Fraud Alert
      
      A high-risk transaction has been detected.
      
      Transaction Details:
      - Player: {{playerName}} (ID: {{playerId}})
      - Amount: ${{amount}}
      - Risk Level: {{riskLevel}}
      - Transaction ID: {{transactionId}}
      - Indicators: {{indicators}}
      
      Action Required: Please review this transaction immediately.
    `,
  },
  high_value_transaction: {
    type: 'high_value_transaction',
    subject: '[ADMIN] High Value Transaction',
    htmlTemplate: `
      <h2>High Value Transaction</h2>
      <p>A high-value transaction has been processed.</p>
      <p><strong>Transaction Details:</strong></p>
      <ul>
        <li>Player: {{playerName}} (ID: {{playerId}})</li>
        <li>Amount: ${{amount}}</li>
        <li>Transaction ID: {{transactionId}}</li>
        <li>Timestamp: {{timestamp}}</li>
      </ul>
      <p>This transaction exceeds your high-value threshold.</p>
    `,
    textTemplate: `
      High Value Transaction
      
      A high-value transaction has been processed.
      
      Transaction Details:
      - Player: {{playerName}} (ID: {{playerId}})
      - Amount: ${{amount}}
      - Transaction ID: {{transactionId}}
      - Timestamp: {{timestamp}}
      
      This transaction exceeds your high-value threshold.
    `,
  },
  refund_processed: {
    type: 'refund_processed',
    subject: 'Refund Processed',
    htmlTemplate: `
      <h2>Refund Processed</h2>
      <p>Hello {{playerName}},</p>
      <p>Your refund has been successfully processed.</p>
      <p><strong>Refund Details:</strong></p>
      <ul>
        <li>Amount: ${{amount}}</li>
        <li>Original Transaction: {{originalTransactionId}}</li>
        <li>Refund ID: {{refundId}}</li>
        <li>Status: Completed</li>
      </ul>
      <p>The refund should appear in your account within 3-5 business days.</p>
      <p>Best regards,<br/>CoinKrazy Team</p>
    `,
    textTemplate: `
      Refund Processed
      
      Hello {{playerName}},
      
      Your refund has been successfully processed.
      
      Refund Details:
      - Amount: ${{amount}}
      - Original Transaction: {{originalTransactionId}}
      - Refund ID: {{refundId}}
      - Status: Completed
      
      The refund should appear in your account within 3-5 business days.
      
      Best regards,
      CoinKrazy Team
    `,
  },
};

/**
 * Render email template with data
 */
export function renderEmailTemplate(
  template: EmailTemplate,
  data: Record<string, any>
): { subject: string; html: string; text: string } {
  let subject = template.subject;
  let html = template.htmlTemplate;
  let text = template.textTemplate;

  // Replace all placeholders
  Object.entries(data).forEach(([key, value]) => {
    const placeholder = new RegExp(`{{${key}}}`, 'g');
    const stringValue = String(value);
    subject = subject.replace(placeholder, stringValue);
    html = html.replace(placeholder, stringValue);
    text = text.replace(placeholder, stringValue);
  });

  return { subject, html, text };
}

/**
 * Send email via Brevo
 */
export async function sendEmailViaBrevo(
  toEmail: string,
  toName: string,
  subject: string,
  htmlContent: string,
  textContent: string
): Promise<{ success: boolean; messageId?: string; error?: string }> {
  try {
    const brevoApiKey = process.env.BREVO_SMTP_PASS;
    if (!brevoApiKey) {
      return { success: false, error: 'Brevo API key not configured' };
    }

    // Use Brevo API endpoint
    const response = await fetch('https://api.brevo.com/v3/smtp/email', {
      method: 'POST',
      headers: {
        'api-key': brevoApiKey,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        to: [{ email: toEmail, name: toName }],
        sender: { email: 'noreply@coinkrazy.com', name: 'CoinKrazy' },
        subject,
        htmlContent,
        textContent,
        replyTo: { email: 'support@coinkrazy.com', name: 'CoinKrazy Support' },
      }),
    });

    if (!response.ok) {
      const error = await response.text();
      return { success: false, error: `Brevo API error: ${error}` };
    }

    const result = await response.json() as { messageId: string };
    return { success: true, messageId: result.messageId };
  } catch (error) {
    return { success: false, error: (error as Error).message };
  }
}

/**
 * Create and send email notification
 */
export async function sendEmailNotification(
  type: EmailNotificationType,
  recipientEmail: string,
  recipientName: string,
  data: Record<string, any>
): Promise<EmailNotification> {
  const template = EMAIL_TEMPLATES[type];
  if (!template) {
    throw new Error(`Unknown email template type: ${type}`);
  }

  const { subject, html, text } = renderEmailTemplate(template, data);

  const notification: EmailNotification = {
    id: `email_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
    type,
    recipientEmail,
    recipientName,
    subject,
    htmlContent: html,
    textContent: text,
    data,
    status: 'pending',
    retryCount: 0,
    maxRetries: 3,
  };

  // Send email
  const result = await sendEmailViaBrevo(recipientEmail, recipientName, subject, html, text);

  if (result.success) {
    notification.status = 'sent';
    notification.sentAt = new Date();
  } else {
    notification.status = 'failed';
    notification.failureReason = result.error;
  }

  return notification;
}

/**
 * Retry failed email notification
 */
export async function retryEmailNotification(
  notification: EmailNotification
): Promise<EmailNotification> {
  if (notification.retryCount >= notification.maxRetries) {
    notification.status = 'failed';
    notification.failureReason = 'Max retries exceeded';
    return notification;
  }

  notification.retryCount++;

  const result = await sendEmailViaBrevo(
    notification.recipientEmail,
    notification.recipientName,
    notification.subject,
    notification.htmlContent,
    notification.textContent
  );

  if (result.success) {
    notification.status = 'sent';
    notification.sentAt = new Date();
  } else {
    notification.failureReason = result.error;
  }

  return notification;
}

/**
 * Send admin notification for withdrawal
 */
export async function notifyAdminWithdrawal(
  adminEmail: string,
  withdrawalData: {
    playerId: number;
    playerName: string;
    playerEmail: string;
    amount: number;
    currency: string;
    method: string;
    withdrawalId: string;
    status: string;
  }
): Promise<EmailNotification> {
  const subject = `[ADMIN] New Withdrawal Request - ${withdrawalData.playerName}`;
  const htmlContent = `
    <h2>New Withdrawal Request</h2>
    <p><strong>Player:</strong> ${withdrawalData.playerName} (${withdrawalData.playerEmail})</p>
    <p><strong>Amount:</strong> ${withdrawalData.amount} ${withdrawalData.currency}</p>
    <p><strong>Method:</strong> ${withdrawalData.method}</p>
    <p><strong>Request ID:</strong> ${withdrawalData.withdrawalId}</p>
    <p><strong>Status:</strong> ${withdrawalData.status}</p>
    <p><a href="https://coinkrazy.com/admin/withdrawals">Review in Dashboard</a></p>
  `;

  const textContent = `
    New Withdrawal Request
    
    Player: ${withdrawalData.playerName} (${withdrawalData.playerEmail})
    Amount: ${withdrawalData.amount} ${withdrawalData.currency}
    Method: ${withdrawalData.method}
    Request ID: ${withdrawalData.withdrawalId}
    Status: ${withdrawalData.status}
  `;

  return {
    id: `admin_email_${Date.now()}`,
    type: 'withdrawal_requested',
    recipientEmail: adminEmail,
    recipientName: 'Admin',
    subject,
    htmlContent,
    textContent,
    data: withdrawalData,
    status: 'pending',
    retryCount: 0,
    maxRetries: 3,
  };
}

/**
 * Send admin notification for fraud alert
 */
export async function notifyAdminFraud(
  adminEmail: string,
  fraudData: {
    playerId: number;
    playerName: string;
    transactionId: string;
    amount: number;
    riskLevel: string;
    indicators: string[];
  }
): Promise<EmailNotification> {
  const subject = `[URGENT] Fraud Alert - ${fraudData.riskLevel.toUpperCase()} Risk`;
  const htmlContent = `
    <h2>Fraud Alert - Immediate Action Required</h2>
    <p><strong>Player:</strong> ${fraudData.playerName} (ID: ${fraudData.playerId})</p>
    <p><strong>Amount:</strong> $${fraudData.amount}</p>
    <p><strong>Risk Level:</strong> <span style="color: red; font-weight: bold;">${fraudData.riskLevel}</span></p>
    <p><strong>Transaction ID:</strong> ${fraudData.transactionId}</p>
    <p><strong>Indicators:</strong> ${fraudData.indicators.join(', ')}</p>
    <p><a href="https://coinkrazy.com/admin/fraud">Review in Dashboard</a></p>
  `;

  const textContent = `
    Fraud Alert - Immediate Action Required
    
    Player: ${fraudData.playerName} (ID: ${fraudData.playerId})
    Amount: $${fraudData.amount}
    Risk Level: ${fraudData.riskLevel}
    Transaction ID: ${fraudData.transactionId}
    Indicators: ${fraudData.indicators.join(', ')}
  `;

  return {
    id: `fraud_alert_${Date.now()}`,
    type: 'fraud_alert',
    recipientEmail: adminEmail,
    recipientName: 'Admin',
    subject,
    htmlContent,
    textContent,
    data: fraudData,
    status: 'pending',
    retryCount: 0,
    maxRetries: 3,
  };
}
