/**
 * Email Notifications Module
 *
 * High-level notification flows that combine templates with sending.
 */

import { sendEmail } from './core';
import {
  createOTPEmail,
  createWelcomeEmail,
  createPasswordResetEmail,
  createDemoConfirmationEmail,
  type Language,
  type OtpPurpose,
} from './templates';
import { logger } from '@/lib/logger';

// =============================================================================
// OTP Notifications
// =============================================================================

/**
 * Send OTP email for login/signup/reset
 */
export async function sendOTPNotification(params: {
  to: string;
  otp: string;
  language: Language;
  name?: string;
  purpose?: OtpPurpose;
}): Promise<boolean> {
  const { to, otp, language, name, purpose = 'login' } = params;

  const template = createOTPEmail(otp, language, name, purpose);
  const result = await sendEmail(to, template);

  if (result) {
    logger.info('OTP email sent', { to, purpose });
  } else {
    logger.error('Failed to send OTP email', { to, purpose });
  }

  return result;
}

/**
 * Send login OTP
 */
export async function sendLoginOTP(
  to: string,
  otp: string,
  language: Language,
  name?: string
): Promise<boolean> {
  return sendOTPNotification({ to, otp, language, name, purpose: 'login' });
}

/**
 * Send signup OTP
 */
export async function sendSignupOTP(
  to: string,
  otp: string,
  language: Language,
  name?: string
): Promise<boolean> {
  return sendOTPNotification({ to, otp, language, name, purpose: 'signup' });
}

/**
 * Send password reset OTP
 */
export async function sendPasswordResetOTP(
  to: string,
  otp: string,
  language: Language
): Promise<boolean> {
  const template = createPasswordResetEmail(otp, language);
  return sendEmail(to, template);
}

// =============================================================================
// Welcome Notifications
// =============================================================================

/**
 * Send welcome email after signup
 */
export async function sendWelcomeNotification(params: {
  to: string;
  name: string;
  language: Language;
}): Promise<boolean> {
  const { to, name, language } = params;

  const template = createWelcomeEmail(name, language);
  const result = await sendEmail(to, template);

  if (result) {
    logger.info('Welcome email sent', { to, name });
  } else {
    logger.error('Failed to send welcome email', { to, name });
  }

  return result;
}

// =============================================================================
// Demo Notifications
// =============================================================================

/**
 * Send demo confirmation email
 */
export async function sendDemoConfirmation(params: {
  to: string;
  name: string;
  date: string;
  time: string;
  duration: string;
  language: Language;
}): Promise<boolean> {
  const { to, name, date, time, duration, language } = params;

  const template = createDemoConfirmationEmail(name, date, time, duration, language);
  const result = await sendEmail(to, template);

  if (result) {
    logger.info('Demo confirmation sent', { to, name, date, time });
  } else {
    logger.error('Failed to send demo confirmation', { to, name });
  }

  return result;
}

// =============================================================================
// Trial Notifications
// =============================================================================

/**
 * Send trial expiring soon notification
 */
export async function sendTrialExpiringNotification(params: {
  to: string;
  name: string;
  daysRemaining: number;
  language: Language;
}): Promise<boolean> {
  const { to, name, daysRemaining, language } = params;
  const isArabic = language === 'ar';
  const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:9000';

  const template = {
    subject: isArabic
      ? `تذكير: تنتهي فترة التجربة خلال ${daysRemaining} أيام`
      : `Reminder: Your trial expires in ${daysRemaining} days`,
    html: `
      <!DOCTYPE html>
      <html ${isArabic ? 'dir="rtl" lang="ar"' : 'lang="en"'}>
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <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, #10b981 0%, #059669 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }
          .content { background: #f9fafb; padding: 30px; border-radius: 0 0 8px 8px; }
          .cta-button { display: inline-block; background: #10b981; color: white; padding: 12px 30px; text-decoration: none; border-radius: 6px; margin: 20px 0; }
          .alert { background: #fef3c7; border: 1px solid #f59e0b; padding: 16px; border-radius: 8px; margin: 20px 0; }
          .footer { text-align: center; margin-top: 20px; color: #6b7280; font-size: 14px; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>${isArabic ? '⏰ تذكير الفترة التجريبية' : '⏰ Trial Reminder'}</h1>
          </div>
          <div class="content">
            <p>${isArabic ? `مرحباً ${name}،` : `Hello ${name},`}</p>
            <div class="alert">
              <p><strong>${
                isArabic
                  ? `تنتهي فترة التجربة المجانية خلال ${daysRemaining} أيام!`
                  : `Your free trial expires in ${daysRemaining} days!`
              }</strong></p>
            </div>
            <p>${
              isArabic
                ? 'قم بالترقية الآن للاستمرار في استخدام جميع الميزات.'
                : 'Upgrade now to continue using all features.'
            }</p>
            <a href="${appUrl}/${language}/dashboard?tab=billing" class="cta-button">
              ${isArabic ? 'الترقية الآن' : 'Upgrade Now'}
            </a>
          </div>
          <div class="footer">
            <p>© ${new Date().getFullYear()} Mawidi. ${isArabic ? 'جميع الحقوق محفوظة.' : 'All rights reserved.'}</p>
          </div>
        </div>
      </body>
      </html>
    `,
    text: isArabic
      ? `مرحباً ${name}،\n\nتنتهي فترة التجربة المجانية خلال ${daysRemaining} أيام!\n\nقم بالترقية الآن للاستمرار في استخدام جميع الميزات.\n\nزيارة: ${appUrl}/${language}/dashboard?tab=billing\n\n© ${new Date().getFullYear()} Mawidi`
      : `Hello ${name},\n\nYour free trial expires in ${daysRemaining} days!\n\nUpgrade now to continue using all features.\n\nVisit: ${appUrl}/${language}/dashboard?tab=billing\n\n© ${new Date().getFullYear()} Mawidi`,
  };

  const result = await sendEmail(to, template);

  if (result) {
    logger.info('Trial expiring notification sent', { to, daysRemaining });
  } else {
    logger.error('Failed to send trial expiring notification', { to });
  }

  return result;
}

/**
 * Send trial expired notification
 */
export async function sendTrialExpiredNotification(params: {
  to: string;
  name: string;
  language: Language;
}): Promise<boolean> {
  const { to, name, language } = params;
  const isArabic = language === 'ar';
  const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:9000';

  const template = {
    subject: isArabic
      ? 'انتهت فترة التجربة المجانية - Mawidi'
      : 'Your Free Trial Has Expired - Mawidi',
    html: `
      <!DOCTYPE html>
      <html ${isArabic ? 'dir="rtl" lang="ar"' : 'lang="en"'}>
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <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, #ef4444 0%, #dc2626 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }
          .content { background: #f9fafb; padding: 30px; border-radius: 0 0 8px 8px; }
          .cta-button { display: inline-block; background: #10b981; color: white; padding: 12px 30px; text-decoration: none; border-radius: 6px; margin: 20px 0; }
          .footer { text-align: center; margin-top: 20px; color: #6b7280; font-size: 14px; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>${isArabic ? '⚠️ انتهت الفترة التجريبية' : '⚠️ Trial Expired'}</h1>
          </div>
          <div class="content">
            <p>${isArabic ? `مرحباً ${name}،` : `Hello ${name},`}</p>
            <p>${
              isArabic
                ? 'لقد انتهت فترة التجربة المجانية الخاصة بك. للاستمرار في استخدام Mawidi، يرجى الترقية إلى خطة مدفوعة.'
                : 'Your free trial has expired. To continue using Mawidi, please upgrade to a paid plan.'
            }</p>
            <a href="${appUrl}/${language}/dashboard?tab=billing" class="cta-button">
              ${isArabic ? 'الترقية الآن' : 'Upgrade Now'}
            </a>
          </div>
          <div class="footer">
            <p>© ${new Date().getFullYear()} Mawidi. ${isArabic ? 'جميع الحقوق محفوظة.' : 'All rights reserved.'}</p>
          </div>
        </div>
      </body>
      </html>
    `,
    text: isArabic
      ? `مرحباً ${name}،\n\nلقد انتهت فترة التجربة المجانية الخاصة بك.\n\nللاستمرار في استخدام Mawidi، يرجى الترقية إلى خطة مدفوعة.\n\nزيارة: ${appUrl}/${language}/dashboard?tab=billing\n\n© ${new Date().getFullYear()} Mawidi`
      : `Hello ${name},\n\nYour free trial has expired.\n\nTo continue using Mawidi, please upgrade to a paid plan.\n\nVisit: ${appUrl}/${language}/dashboard?tab=billing\n\n© ${new Date().getFullYear()} Mawidi`,
  };

  const result = await sendEmail(to, template);

  if (result) {
    logger.info('Trial expired notification sent', { to });
  } else {
    logger.error('Failed to send trial expired notification', { to });
  }

  return result;
}
