/**
 * Email sending service using Resend
 * Handles all transactional emails (verification, password reset, etc.)
 */

import { Resend } from 'resend';
import {
  verificationEmailTemplate,
  passwordResetEmailTemplate,
  welcomeEmailTemplate,
  teamInviteEmailTemplate,
  paymentFailedEmailTemplate,
  subscriptionConfirmedEmailTemplate,
  spendingAlertEmailTemplate,
  deviceOfflineEmailTemplate,
  budgetAlertEmailTemplate,
  monthlySummaryEmailTemplate,
} from './templates';
import type { VerificationEmailProps, PasswordResetEmailProps, MonthlySummaryEmailProps } from './templates';

// Initialize Resend client
const resend = process.env.RESEND_API_KEY
  ? new Resend(process.env.RESEND_API_KEY)
  : null;

const FROM_EMAIL = process.env.EMAIL_FROM || 'LLMHosts <noreply@llmhosts.com>';

/**
 * Send email verification link to new users
 */
export async function sendVerificationEmail(props: VerificationEmailProps) {
  const { html, text, subject } = verificationEmailTemplate(props);

  // If Resend is not configured, log to console for development
  if (!resend) {
    console.log('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log('📧 EMAIL VERIFICATION (Resend not configured)');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log(`To: ${props.email}`);
    console.log(`Subject: ${subject}`);
    console.log(`Verification URL: ${props.url}`);
    console.log(`Expires: ${props.expires.toISOString()}`);
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    return { success: true, messageId: 'dev-mode' };
  }

  try {
    const { data, error } = await resend.emails.send({
      from: FROM_EMAIL,
      to: props.email,
      subject,
      html,
      text,
    });

    if (error) {
      console.error('Failed to send verification email:', error);
      throw new Error(`Email sending failed: ${error.message}`);
    }

    console.log(`✅ Verification email sent to ${props.email} (ID: ${data?.id})`);
    return { success: true, messageId: data?.id };
  } catch (error) {
    console.error('Failed to send verification email:', error);
    throw error;
  }
}

/**
 * Send password reset link to users
 */
export async function sendPasswordResetEmail(props: PasswordResetEmailProps) {
  const { html, text, subject } = passwordResetEmailTemplate(props);

  // If Resend is not configured, log to console for development
  if (!resend) {
    console.log('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log('🔐 PASSWORD RESET (Resend not configured)');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log(`To: ${props.email}`);
    console.log(`Subject: ${subject}`);
    console.log(`Reset URL: ${props.url}`);
    console.log(`Expires: ${props.expires.toISOString()}`);
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    return { success: true, messageId: 'dev-mode' };
  }

  try {
    const { data, error } = await resend.emails.send({
      from: FROM_EMAIL,
      to: props.email,
      subject,
      html,
      text,
    });

    if (error) {
      console.error('Failed to send password reset email:', error);
      throw new Error(`Email sending failed: ${error.message}`);
    }

    console.log(`✅ Password reset email sent to ${props.email} (ID: ${data?.id})`);
    return { success: true, messageId: data?.id };
  } catch (error) {
    console.error('Failed to send password reset email:', error);
    throw error;
  }
}

/**
 * Resend a verification email if the original was not received
 */
export async function resendVerificationEmail(email: string, token: string) {
  const url = `${process.env.NEXTAUTH_URL}/auth/verify-email?token=${token}&email=${encodeURIComponent(email)}`;
  const expires = new Date(Date.now() + 24 * 60 * 60 * 1000); // 24 hours

  return sendVerificationEmail({ email, url, expires });
}

const CONTACT_TO = 'hello@llmhosts.com';

export interface SendContactEmailProps {
  name: string;
  email: string;
  subject: string;
  message: string;
}

/**
 * Send contact form submission to hello@llmhosts.com.
 * Uses same Resend client as transactional email; no-op when RESEND_API_KEY is unset.
 */
export async function sendContactEmail(props: SendContactEmailProps) {
  const { name, email, subject, message } = props;
  const subjectLine = `[Contact] ${subject} — from ${name}`;
  const text = `Name: ${name}\nEmail: ${email}\nSubject: ${subject}\n\nMessage:\n${message}`;

  if (!resend) {
    console.log('[contact] Resend not configured; would send to', CONTACT_TO, subjectLine);
    return { success: true, messageId: 'dev-mode' };
  }

  try {
    const { data, error } = await resend.emails.send({
      from: FROM_EMAIL,
      to: CONTACT_TO,
      subject: subjectLine,
      text,
    });
    if (error) {
      console.error('[contact] Resend error:', error);
      throw new Error(`Email sending failed: ${error.message}`);
    }
    return { success: true, messageId: data?.id };
  } catch (err) {
    console.error('[contact] Resend error:', err);
    throw err;
  }
}

const BASE_URL = process.env.NEXTAUTH_URL || 'https://llmhosts.com';

/**
 * Send welcome email after email verification completes
 */
export async function sendWelcomeEmail(email: string, name: string) {
  const dashboardUrl = `${BASE_URL}/dashboard`;
  const { html, text, subject } = welcomeEmailTemplate({ name, dashboardUrl });

  if (!resend) {
    console.log('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log('WELCOME EMAIL (Resend not configured)');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log(`To: ${email}`);
    console.log(`Subject: ${subject}`);
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    return { success: true, messageId: 'dev-mode' };
  }

  try {
    const { data, error } = await resend.emails.send({
      from: FROM_EMAIL,
      to: email,
      subject,
      html,
      text,
    });

    if (error) {
      console.error('Failed to send welcome email:', error);
      throw new Error(`Email sending failed: ${error.message}`);
    }

    console.log(`Welcome email sent to ${email} (ID: ${data?.id})`);
    return { success: true, messageId: data?.id };
  } catch (error) {
    console.error('Failed to send welcome email:', error);
    throw error;
  }
}

/**
 * Send team invitation email
 */
export async function sendTeamInviteEmail(
  email: string,
  inviterName: string,
  teamName: string,
  role: string,
  inviteUrl: string
) {
  const { html, text, subject } = teamInviteEmailTemplate({ inviterName, teamName, role, inviteUrl });

  if (!resend) {
    console.log('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log('TEAM INVITE (Resend not configured)');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log(`To: ${email}`);
    console.log(`Subject: ${subject}`);
    console.log(`Invite URL: ${inviteUrl}`);
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    return { success: true, messageId: 'dev-mode' };
  }

  try {
    const { data, error } = await resend.emails.send({
      from: FROM_EMAIL,
      to: email,
      subject,
      html,
      text,
    });

    if (error) {
      console.error('Failed to send team invite email:', error);
      throw new Error(`Email sending failed: ${error.message}`);
    }

    console.log(`Team invite email sent to ${email} (ID: ${data?.id})`);
    return { success: true, messageId: data?.id };
  } catch (error) {
    console.error('Failed to send team invite email:', error);
    throw error;
  }
}

/**
 * Send payment failed notification
 */
export async function sendPaymentFailedEmail(email: string, name: string) {
  const billingUrl = `${BASE_URL}/dashboard/settings/billing`;
  const { html, text, subject } = paymentFailedEmailTemplate({ name, billingUrl });

  if (!resend) {
    console.log('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log('PAYMENT FAILED (Resend not configured)');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log(`To: ${email}`);
    console.log(`Subject: ${subject}`);
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    return { success: true, messageId: 'dev-mode' };
  }

  try {
    const { data, error } = await resend.emails.send({
      from: FROM_EMAIL,
      to: email,
      subject,
      html,
      text,
    });

    if (error) {
      console.error('Failed to send payment failed email:', error);
      throw new Error(`Email sending failed: ${error.message}`);
    }

    console.log(`Payment failed email sent to ${email} (ID: ${data?.id})`);
    return { success: true, messageId: data?.id };
  } catch (error) {
    console.error('Failed to send payment failed email:', error);
    throw error;
  }
}

/**
 * Send subscription confirmed email after successful checkout
 */
export async function sendSubscriptionConfirmedEmail(
  email: string,
  name: string,
  planName: string,
  features: string[]
) {
  const dashboardUrl = `${BASE_URL}/dashboard`;
  const { html, text, subject } = subscriptionConfirmedEmailTemplate({ name, planName, features, dashboardUrl });

  if (!resend) {
    console.log('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log('SUBSCRIPTION CONFIRMED (Resend not configured)');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log(`To: ${email}`);
    console.log(`Subject: ${subject}`);
    console.log(`Plan: ${planName}`);
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    return { success: true, messageId: 'dev-mode' };
  }

  try {
    const { data, error } = await resend.emails.send({
      from: FROM_EMAIL,
      to: email,
      subject,
      html,
      text,
    });

    if (error) {
      console.error('Failed to send subscription confirmed email:', error);
      throw new Error(`Email sending failed: ${error.message}`);
    }

    console.log(`Subscription confirmed email sent to ${email} (ID: ${data?.id})`);
    return { success: true, messageId: data?.id };
  } catch (error) {
    console.error('Failed to send subscription confirmed email:', error);
    throw error;
  }
}

/**
 * Send spending alert when team exceeds budget threshold
 */
export async function sendSpendingAlertEmail(
  email: string,
  teamName: string,
  currentSpend: number,
  budget: number,
  percentage: number
) {
  const usageUrl = `${BASE_URL}/dashboard/usage`;
  const { html, text, subject } = spendingAlertEmailTemplate({ teamName, currentSpend, budget, percentage, usageUrl });

  if (!resend) {
    console.log('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log('SPENDING ALERT (Resend not configured)');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log(`To: ${email}`);
    console.log(`Subject: ${subject}`);
    console.log(`Team: ${teamName} | Spend: $${currentSpend.toFixed(2)} / $${budget.toFixed(2)} (${percentage}%)`);
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    return { success: true, messageId: 'dev-mode' };
  }

  try {
    const { data, error } = await resend.emails.send({
      from: FROM_EMAIL,
      to: email,
      subject,
      html,
      text,
    });

    if (error) {
      console.error('Failed to send spending alert email:', error);
      throw new Error(`Email sending failed: ${error.message}`);
    }

    console.log(`Spending alert email sent to ${email} (ID: ${data?.id})`);
    return { success: true, messageId: data?.id };
  } catch (error) {
    console.error('Failed to send spending alert email:', error);
    throw error;
  }
}

/**
 * Send device offline alert email
 */
export async function sendDeviceOfflineEmail(
  email: string,
  name: string,
  deviceName: string,
  lastSeen: Date,
) {
  const dashboardUrl = `${BASE_URL}/dashboard`;
  const { html, text, subject } = deviceOfflineEmailTemplate({ name, deviceName, lastSeen, dashboardUrl });

  if (!resend) {
    console.log('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log('DEVICE OFFLINE ALERT (Resend not configured)');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log(`To: ${email}`);
    console.log(`Subject: ${subject}`);
    console.log(`Device: ${deviceName} | Last seen: ${lastSeen.toISOString()}`);
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    return { success: true, messageId: 'dev-mode' };
  }

  try {
    const { data, error } = await resend.emails.send({
      from: FROM_EMAIL,
      to: email,
      subject,
      html,
      text,
    });

    if (error) {
      console.error('Failed to send device offline email:', error);
      throw new Error(`Email sending failed: ${error.message}`);
    }

    console.log(`Device offline email sent to ${email} (ID: ${data?.id})`);
    return { success: true, messageId: data?.id };
  } catch (error) {
    console.error('Failed to send device offline email:', error);
    throw error;
  }
}

/**
 * Send Token budget threshold alert email
 */
export async function sendBudgetAlertEmail(
  email: string,
  name: string,
  currentSpend: number,
  budgetLimit: number,
  percentUsed: number,
) {
  const dashboardUrl = `${BASE_URL}/dashboard/token`;
  const { html, text, subject } = budgetAlertEmailTemplate({
    name,
    currentSpend,
    budgetLimit,
    percentUsed,
    dashboardUrl,
  });

  if (!resend) {
    console.log('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log('BUDGET ALERT (Resend not configured)');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log(`To: ${email}`);
    console.log(`Subject: ${subject}`);
    console.log(`Spend: $${currentSpend.toFixed(2)} / $${budgetLimit.toFixed(2)} (${percentUsed}%)`);
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    return { success: true, messageId: 'dev-mode' };
  }

  try {
    const { data, error } = await resend.emails.send({
      from: FROM_EMAIL,
      to: email,
      subject,
      html,
      text,
    });

    if (error) {
      console.error('Failed to send budget alert email:', error);
      throw new Error(`Email sending failed: ${error.message}`);
    }

    console.log(`Budget alert email sent to ${email} (ID: ${data?.id})`);
    return { success: true, messageId: data?.id };
  } catch (error) {
    console.error('Failed to send budget alert email:', error);
    throw error;
  }
}

/**
 * Send monthly Token usage summary email
 */
export async function sendMonthlySummaryEmail(
  email: string,
  props: Omit<MonthlySummaryEmailProps, 'dashboardUrl'>,
) {
  const dashboardUrl = `${BASE_URL}/dashboard/token`;
  const { html, text, subject } = monthlySummaryEmailTemplate({ ...props, dashboardUrl });

  if (!resend) {
    console.log('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log('MONTHLY SUMMARY (Resend not configured)');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log(`To: ${email}`);
    console.log(`Subject: ${subject}`);
    console.log(`Month: ${props.month} | Messages: ${props.totalMessages} | Cost: $${props.totalCost.toFixed(2)}`);
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    return { success: true, messageId: 'dev-mode' };
  }

  try {
    const { data, error } = await resend.emails.send({
      from: FROM_EMAIL,
      to: email,
      subject,
      html,
      text,
    });

    if (error) {
      console.error('Failed to send monthly summary email:', error);
      throw new Error(`Email sending failed: ${error.message}`);
    }

    console.log(`Monthly summary email sent to ${email} (ID: ${data?.id})`);
    return { success: true, messageId: data?.id };
  } catch (error) {
    console.error('Failed to send monthly summary email:', error);
    throw error;
  }
}
