/**
 * Email Service Integration
 * 
 * This service provides email sending capabilities for admin onboarding notifications.
 * Currently configured as a placeholder - integrate with SendGrid, Mailgun, or AWS SES.
 * 
 * Configuration needed:
 * - EMAIL_PROVIDER: 'sendgrid' | 'mailgun' | 'aws_ses' | 'smtp'
 * - EMAIL_API_KEY: Provider-specific API key
 * - EMAIL_FROM_ADDRESS: Sender email address
 * - EMAIL_FROM_NAME: Sender display name
 */

export interface EmailOptions {
  to: string;
  subject: string;
  html: string;
  text?: string;
  replyTo?: string;
  cc?: string[];
  bcc?: string[];
}

export interface SendEmailResult {
  success: boolean;
  messageId?: string;
  error?: string;
}

/**
 * Send email using configured provider
 * 
 * Supported providers:
 * - sendgrid: SendGrid API
 * - mailgun: Mailgun API
 * - aws_ses: AWS Simple Email Service
 * - smtp: SMTP server (requires SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS)
 */
export async function sendEmail(options: EmailOptions): Promise<SendEmailResult> {
  const provider = process.env.EMAIL_PROVIDER || 'sendgrid';
  const apiKey = process.env.EMAIL_API_KEY;

  if (!apiKey) {
    console.warn('[EmailService] EMAIL_API_KEY not configured');
    return {
      success: false,
      error: 'Email service not configured',
    };
  }

  try {
    switch (provider) {
      case 'sendgrid':
        return await sendViaSendGrid(options, apiKey);
      case 'mailgun':
        return await sendViaMailgun(options, apiKey);
      case 'aws_ses':
        return await sendViaAwsSES(options, apiKey);
      case 'smtp':
        return await sendViaSMTP(options);
      default:
        return {
          success: false,
          error: `Unknown email provider: ${provider}`,
        };
    }
  } catch (error) {
    console.error('[EmailService] Error sending email:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error',
    };
  }
}

/**
 * SendGrid implementation
 * Install: npm install @sendgrid/mail
 */
async function sendViaSendGrid(
  options: EmailOptions,
  apiKey: string
): Promise<SendEmailResult> {
  try {
    // const sgMail = require('@sendgrid/mail');
    // sgMail.setApiKey(apiKey);
    // 
    // const msg = {
    //   to: options.to,
    //   from: process.env.EMAIL_FROM_ADDRESS || 'noreply@playcoinkrazy.com',
    //   subject: options.subject,
    //   html: options.html,
    //   text: options.text,
    //   replyTo: options.replyTo,
    //   cc: options.cc,
    //   bcc: options.bcc,
    // };
    // 
    // const response = await sgMail.send(msg);
    // 
    // return {
    //   success: true,
    //   messageId: response[0].headers['x-message-id'],
    // };

    console.log('[EmailService] SendGrid email sent to:', options.to);
    return { success: true, messageId: 'mock-sendgrid-id' };
  } catch (error) {
    throw error;
  }
}

/**
 * Mailgun implementation
 * Install: npm install mailgun.js
 */
async function sendViaMailgun(
  options: EmailOptions,
  apiKey: string
): Promise<SendEmailResult> {
  try {
    // const mailgun = require('mailgun.js');
    // const FormData = require('form-data');
    // 
    // const client = new mailgun(FormData);
    // const domain = process.env.MAILGUN_DOMAIN || 'playcoinkrazy.com';
    // const mg = client.client({ username: 'api', key: apiKey });
    // 
    // const response = await mg.messages.create(domain, {
    //   from: process.env.EMAIL_FROM_ADDRESS || 'noreply@playcoinkrazy.com',
    //   to: options.to,
    //   subject: options.subject,
    //   html: options.html,
    //   text: options.text,
    //   'h:Reply-To': options.replyTo,
    //   cc: options.cc,
    //   bcc: options.bcc,
    // });
    // 
    // return {
    //   success: true,
    //   messageId: response.id,
    // };

    console.log('[EmailService] Mailgun email sent to:', options.to);
    return { success: true, messageId: 'mock-mailgun-id' };
  } catch (error) {
    throw error;
  }
}

/**
 * AWS SES implementation
 * Install: npm install @aws-sdk/client-ses
 */
async function sendViaAwsSES(
  options: EmailOptions,
  apiKey: string
): Promise<SendEmailResult> {
  try {
    // const { SESClient, SendEmailCommand } = require('@aws-sdk/client-ses');
    // 
    // const client = new SESClient({
    //   region: process.env.AWS_REGION || 'us-east-1',
    //   credentials: {
    //     accessKeyId: process.env.AWS_ACCESS_KEY_ID || '',
    //     secretAccessKey: apiKey,
    //   },
    // });
    // 
    // const command = new SendEmailCommand({
    //   Source: process.env.EMAIL_FROM_ADDRESS || 'noreply@playcoinkrazy.com',
    //   Destination: {
    //     ToAddresses: [options.to],
    //     CcAddresses: options.cc,
    //     BccAddresses: options.bcc,
    //   },
    //   Message: {
    //     Subject: { Data: options.subject },
    //     Body: {
    //       Html: { Data: options.html },
    //       Text: { Data: options.text || options.html },
    //     },
    //   },
    //   ReplyToAddresses: options.replyTo ? [options.replyTo] : undefined,
    // });
    // 
    // const response = await client.send(command);
    // 
    // return {
    //   success: true,
    //   messageId: response.MessageId,
    // };

    console.log('[EmailService] AWS SES email sent to:', options.to);
    return { success: true, messageId: 'mock-ses-id' };
  } catch (error) {
    throw error;
  }
}

/**
 * SMTP implementation
 * Install: npm install nodemailer
 */
async function sendViaSMTP(options: EmailOptions): Promise<SendEmailResult> {
  try {
    // const nodemailer = require('nodemailer');
    // 
    // const transporter = nodemailer.createTransport({
    //   host: process.env.SMTP_HOST,
    //   port: parseInt(process.env.SMTP_PORT || '587'),
    //   secure: process.env.SMTP_SECURE === 'true',
    //   auth: {
    //     user: process.env.SMTP_USER,
    //     pass: process.env.SMTP_PASS,
    //   },
    // });
    // 
    // const response = await transporter.sendMail({
    //   from: process.env.EMAIL_FROM_ADDRESS || 'noreply@playcoinkrazy.com',
    //   to: options.to,
    //   subject: options.subject,
    //   html: options.html,
    //   text: options.text,
    //   replyTo: options.replyTo,
    //   cc: options.cc,
    //   bcc: options.bcc,
    // });
    // 
    // return {
    //   success: true,
    //   messageId: response.messageId,
    // };

    console.log('[EmailService] SMTP email sent to:', options.to);
    return { success: true, messageId: 'mock-smtp-id' };
  } catch (error) {
    throw error;
  }
}

/**
 * Generate HTML email template for admin welcome
 */
export function generateWelcomeEmailTemplate(
  adminName: string,
  role: string,
  onboardingUrl: string
): string {
  return `
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <style>
          body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
          .container { max-width: 600px; margin: 0 auto; padding: 20px; }
          .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 8px 8px 0 0; }
          .content { background: #f9f9f9; padding: 20px; border-radius: 0 0 8px 8px; }
          .button { display: inline-block; background: #667eea; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px; margin: 20px 0; }
          .footer { font-size: 12px; color: #999; margin-top: 20px; padding-top: 20px; border-top: 1px solid #ddd; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>Welcome to CoinKrazy Admin Team, ${adminName}!</h1>
          </div>
          <div class="content">
            <p>Hello ${adminName},</p>
            
            <p>Your admin account has been created with the role: <strong>${role}</strong></p>
            
            <p>To get started, please complete your onboarding process by clicking the button below:</p>
            
            <a href="${onboardingUrl}" class="button">Start Onboarding</a>
            
            <h3>What's Included in Your Onboarding:</h3>
            <ul>
              <li>Role assignment and permission review</li>
              <li>Security training and quiz</li>
              <li>Device registration and IP whitelist</li>
              <li>Two-factor authentication setup</li>
              <li>Profile customization</li>
            </ul>
            
            <p><strong>Important:</strong> This invite link expires in 7 days. Please complete your onboarding before then.</p>
            
            <p>If you have any questions, please contact our support team at support@playcoinkrazy.com</p>
            
            <div class="footer">
              <p>© 2026 CoinKrazy. All rights reserved.</p>
              <p>This is an automated message. Please do not reply to this email.</p>
            </div>
          </div>
        </div>
      </body>
    </html>
  `;
}

/**
 * Generate HTML email template for security tips
 */
export function generateSecurityTipsTemplate(adminName: string): string {
  return `
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <style>
          body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
          .container { max-width: 600px; margin: 0 auto; padding: 20px; }
          .header { background: #ff6b6b; color: white; padding: 20px; border-radius: 8px 8px 0 0; }
          .content { background: #f9f9f9; padding: 20px; border-radius: 0 0 8px 8px; }
          .tip { background: white; padding: 15px; margin: 10px 0; border-left: 4px solid #ff6b6b; border-radius: 4px; }
          .footer { font-size: 12px; color: #999; margin-top: 20px; padding-top: 20px; border-top: 1px solid #ddd; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>🔒 Security Tips for Admin Accounts</h1>
          </div>
          <div class="content">
            <p>Hi ${adminName},</p>
            
            <p>As a member of our admin team, your account security is critical. Please follow these best practices:</p>
            
            <div class="tip">
              <strong>✓ Enable Two-Factor Authentication (2FA)</strong>
              <p>Always use 2FA on your admin account. This adds an extra layer of security even if your password is compromised.</p>
            </div>
            
            <div class="tip">
              <strong>✓ Use Strong, Unique Passwords</strong>
              <p>Create passwords with at least 12 characters, mixing uppercase, lowercase, numbers, and special characters.</p>
            </div>
            
            <div class="tip">
              <strong>✓ Never Share Credentials</strong>
              <p>Your login credentials are personal. Never share them with anyone, including other admins or support staff.</p>
            </div>
            
            <div class="tip">
              <strong>✓ Report Suspicious Activity</strong>
              <p>If you notice unusual login attempts or suspicious activity, report it immediately to security@playcoinkrazy.com</p>
            </div>
            
            <div class="tip">
              <strong>✓ Keep Your Device Updated</strong>
              <p>Regularly update your operating system, browser, and security software.</p>
            </div>
            
            <div class="tip">
              <strong>✓ Use VPN on Public Networks</strong>
              <p>Always use a VPN when accessing your admin account from public WiFi networks.</p>
            </div>
            
            <div class="footer">
              <p>© 2026 CoinKrazy. All rights reserved.</p>
            </div>
          </div>
        </div>
      </body>
    </html>
  `;
}
