/**
 * Email lifecycle sequences for onboarding and retention.
 *
 * Day 0: Welcome + first API call guide (sent immediately on subscription)
 * Day 3: Activation check + social proof
 * Day 7: Value reminder + urgency
 * Day 12: Trial ending warning (if 14-day trial)
 * Day 15: Post-expiry recovery
 *
 * Production scheduling: these functions are designed to be called from a
 * cron job (e.g. Vercel Cron, external scheduler hitting /api/cron/emails).
 * Day 0 is sent inline from the webhook; Days 3+ require a scheduled scan
 * of users by createdAt / stripeCurrentPeriodEnd.
 *
 * Cron implementation TODO:
 *   POST /api/cron/email-sequences (protected by CRON_SECRET)
 *   1. Query users where plan != 'free' AND no FAE event yet
 *   2. Calculate daysSinceSubscription
 *   3. Call the matching sequence function
 *   4. Record sent emails in UserEvent to avoid duplicates
 */

import { Resend } from 'resend';
import { logger } from '@/lib/logger';

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>';
const BASE_URL = process.env.NEXTAUTH_URL || 'https://llmhosts.com';

interface SendResult {
  success: boolean;
  messageId?: string;
}

async function sendEmail(
  to: string,
  subject: string,
  html: string,
  text: string,
): Promise<SendResult> {
  if (!resend) {
    logger.info(
      { action: 'email_sequence', to, subject },
      'Resend not configured; skipping email',
    );
    return { success: true, messageId: 'dev-mode' };
  }

  try {
    const { data, error } = await resend.emails.send({
      from: FROM_EMAIL,
      to,
      subject,
      html,
      text,
    });
    if (error) {
      logger.error({ action: 'email_sequence', to, subject, error }, 'Failed to send sequence email');
      return { success: false };
    }
    logger.info({ action: 'email_sequence', to, subject, messageId: data?.id }, 'Sequence email sent');
    return { success: true, messageId: data?.id };
  } catch (err) {
    logger.error({ action: 'email_sequence', to, subject, err }, 'Sequence email error');
    return { success: false };
  }
}

function emailWrapper(title: string, body: string): string {
  return `<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>${title}</title></head>
<body style="margin:0;padding:0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif;background-color:#f9fafb;">
<table role="presentation" style="width:100%;border-collapse:collapse;"><tr><td align="center" style="padding:40px 0;">
<table role="presentation" style="width:600px;border-collapse:collapse;background-color:#ffffff;border-radius:8px;box-shadow:0 1px 3px rgba(0,0,0,0.1);">
<tr><td style="padding:40px 40px 20px;text-align:center;background:linear-gradient(to right,#6366f1,#8b5cf6);border-radius:8px 8px 0 0;">
<h1 style="margin:0;color:#ffffff;font-size:28px;font-weight:700;">LLMHosts</h1>
<p style="margin:8px 0 0;color:#e0e7ff;font-size:14px;">Your hardware. Real AI infrastructure.</p>
</td></tr>
<tr><td style="padding:40px;">${body}</td></tr>
<tr><td style="padding:32px 40px;background-color:#f9fafb;border-radius:0 0 8px 8px;text-align:center;">
<p style="margin:0;color:#9ca3af;font-size:12px;">&copy; ${new Date().getFullYear()} LLMHosts. All rights reserved.</p>
</td></tr>
</table></td></tr></table></body></html>`;
}

function ctaButton(href: string, label: string): string {
  return `<table role="presentation" style="margin:24px 0;"><tr>
<td style="border-radius:6px;background:linear-gradient(to right,#6366f1,#8b5cf6);">
<a href="${href}" style="display:inline-block;padding:14px 28px;color:#ffffff;text-decoration:none;font-weight:600;font-size:16px;">${label}</a>
</td></tr></table>`;
}

// ---------------------------------------------------------------------------
// Day 0 — Welcome + first API call guide
// ---------------------------------------------------------------------------
export async function sendDay0Welcome(
  email: string,
  name: string,
  planName: string,
): Promise<SendResult> {
  const keysUrl = `${BASE_URL}/dashboard/keys`;
  const subject = `Welcome to LLMHosts, ${name}! Here's how to make your first API call`;

  const body = `
<h2 style="margin:0 0 16px;color:#111827;font-size:22px;font-weight:600;">You're in, ${name}!</h2>
<p style="margin:0 0 16px;color:#6b7280;font-size:16px;line-height:24px;">
  Your <strong>${planName}</strong> plan is active. Let's get your first API call working in under 5 minutes.
</p>
<p style="margin:0 0 8px;color:#111827;font-size:15px;font-weight:600;">Step 1: Create an API key</p>
<p style="margin:0 0 16px;color:#6b7280;font-size:14px;">Go to <a href="${keysUrl}" style="color:#6366f1;">Dashboard &gt; API Keys</a> and create a key.</p>
<p style="margin:0 0 8px;color:#111827;font-size:15px;font-weight:600;">Step 2: Connect your GPU</p>
<div style="background:#1f2937;border-radius:6px;padding:12px 16px;margin:0 0 16px;">
  <code style="color:#e5e7eb;font-size:13px;">pip install llmhosts && llmhosts up</code>
</div>
<p style="margin:0 0 8px;color:#111827;font-size:15px;font-weight:600;">Step 3: Make your first call</p>
<div style="background:#1f2937;border-radius:6px;padding:12px 16px;margin:0 0 16px;">
  <code style="color:#e5e7eb;font-size:13px;">curl https://llmhosts.com/v1/chat/completions \\<br>&nbsp;&nbsp;-H "Authorization: Bearer lh_sk_..." \\<br>&nbsp;&nbsp;-d '{"model":"llama3.2","messages":[{"role":"user","content":"Hello"}]}'</code>
</div>
${ctaButton(keysUrl, 'Create API Key')}
<p style="margin:24px 0 0;color:#9ca3af;font-size:13px;">Need help? Reply to this email — we read every message.</p>`;

  const text = `Welcome to LLMHosts, ${name}!

Your ${planName} plan is active. Get your first API call working in under 5 minutes:

1. Create an API key: ${keysUrl}
2. Connect your GPU: pip install llmhosts && llmhosts up
3. Make your first call with curl or the OpenAI SDK

Get started: ${keysUrl}

Need help? Reply to this email.`;

  return sendEmail(email, subject, emailWrapper(subject, body), text);
}

// ---------------------------------------------------------------------------
// Day 3 — Activation check + social proof
// ---------------------------------------------------------------------------
export async function sendDay3Activation(
  email: string,
  name: string,
  hasActivated: boolean,
): Promise<SendResult> {
  const dashboardUrl = `${BASE_URL}/dashboard`;

  if (hasActivated) {
    // Already activated — send a positive reinforcement email
    const subject = `Nice work, ${name}! You're saving on AI costs`;
    const body = `
<h2 style="margin:0 0 16px;color:#111827;font-size:22px;font-weight:600;">You're off to a great start</h2>
<p style="margin:0 0 16px;color:#6b7280;font-size:16px;line-height:24px;">
  You've already made your first API call through LLMHosts. Users who connect early
  typically save 35% or more on AI costs within the first month.
</p>
<p style="margin:0 0 16px;color:#6b7280;font-size:14px;">
  <strong>Next step:</strong> Connect a second GPU or explore the marketplace to access more models.
</p>
${ctaButton(dashboardUrl, 'Open Dashboard')}`;
    const text = `Great start, ${name}! You've made your first API call. Users save 35%+ within the first month.\n\nNext: connect a second GPU or explore the marketplace.\n\n${dashboardUrl}`;
    return sendEmail(email, subject, emailWrapper(subject, body), text);
  }

  // Not activated yet — nudge
  const subject = `${name}, your GPU is waiting — make your first API call`;
  const body = `
<h2 style="margin:0 0 16px;color:#111827;font-size:22px;font-weight:600;">One step away from savings</h2>
<p style="margin:0 0 16px;color:#6b7280;font-size:16px;line-height:24px;">
  You signed up 3 days ago but haven't made your first API call yet.
  Most users get set up in under 5 minutes:
</p>
<div style="background:#f3f4f6;border-radius:6px;padding:16px;margin:0 0 16px;">
  <p style="margin:0;color:#111827;font-size:14px;"><strong>Teams using LLMHosts report:</strong></p>
  <p style="margin:8px 0 0;color:#6b7280;font-size:14px;">35% average cost reduction on AI API spend</p>
  <p style="margin:4px 0 0;color:#6b7280;font-size:14px;">Sub-15ms cache hits on repeated queries</p>
  <p style="margin:4px 0 0;color:#6b7280;font-size:14px;">Full privacy — PII never leaves your network</p>
</div>
${ctaButton(`${BASE_URL}/dashboard/keys`, 'Create Your First API Key')}`;
  const text = `Hi ${name}, you signed up 3 days ago but haven't made your first API call yet.\n\nTeams report 35% cost savings. Get started: ${BASE_URL}/dashboard/keys`;
  return sendEmail(email, subject, emailWrapper(subject, body), text);
}

// ---------------------------------------------------------------------------
// Day 7 — Urgency + value reminder
// ---------------------------------------------------------------------------
export async function sendDay7Urgency(
  email: string,
  name: string,
  hasActivated: boolean,
  daysLeft: number,
): Promise<SendResult> {
  if (hasActivated) return { success: true }; // skip if already activated

  const subject = `${name}, ${daysLeft} days left to experience LLMHosts`;
  const body = `
<h2 style="margin:0 0 16px;color:#111827;font-size:22px;font-weight:600;">${daysLeft} days remaining</h2>
<p style="margin:0 0 16px;color:#6b7280;font-size:16px;line-height:24px;">
  Your trial still has ${daysLeft} days. Users who make their first API call within the first week
  are <strong>3x more likely</strong> to see meaningful savings.
</p>
<p style="margin:0 0 8px;color:#111827;font-size:15px;font-weight:600;">Quickest path:</p>
<div style="background:#1f2937;border-radius:6px;padding:12px 16px;margin:0 0 16px;">
  <code style="color:#e5e7eb;font-size:13px;">pip install llmhosts && llmhosts up</code>
</div>
<p style="margin:0 0 16px;color:#6b7280;font-size:14px;">
  This single command installs the CLI, auto-discovers your GPU, and registers it. Then create an API key in the dashboard and you're live.
</p>
${ctaButton(`${BASE_URL}/dashboard`, 'Open Dashboard')}`;
  const text = `Hi ${name}, your trial has ${daysLeft} days left.\n\nUsers who activate in week 1 are 3x more likely to see savings.\n\nQuick start: pip install llmhosts && llmhosts up\n\nDashboard: ${BASE_URL}/dashboard`;
  return sendEmail(email, subject, emailWrapper(subject, body), text);
}

// ---------------------------------------------------------------------------
// Day 12 — Trial ending warning (2 days before 14-day trial ends)
// ---------------------------------------------------------------------------
export async function sendTrialEndingWarning(
  email: string,
  name: string,
  daysLeft: number,
): Promise<SendResult> {
  const subject = `${name}, your LLMHosts trial ends in ${daysLeft} days`;
  const body = `
<h2 style="margin:0 0 16px;color:#111827;font-size:22px;font-weight:600;">Your trial ends in ${daysLeft} days</h2>
<p style="margin:0 0 16px;color:#6b7280;font-size:16px;line-height:24px;">
  After your trial ends, your account will revert to the Free plan. Your API keys and devices will remain,
  but you'll lose access to Pro features including advanced routing and priority support.
</p>
<p style="margin:0 0 16px;color:#6b7280;font-size:14px;">
  To keep your current plan, no action needed — your card on file will be charged automatically.
  To cancel, visit Settings before your trial ends.
</p>
${ctaButton(`${BASE_URL}/dashboard`, 'Review Your Plan')}`;
  const text = `Hi ${name}, your trial ends in ${daysLeft} days.\n\nAfter that you'll revert to Free. To keep Pro, no action needed.\n\nReview: ${BASE_URL}/dashboard`;
  return sendEmail(email, subject, emailWrapper(subject, body), text);
}

// ---------------------------------------------------------------------------
// Day 15 — Post-expiry recovery (1 day after trial ends)
// ---------------------------------------------------------------------------
export async function sendPostExpiryRecovery(
  email: string,
  name: string,
): Promise<SendResult> {
  const pricingUrl = `${BASE_URL}/pricing`;
  const subject = `${name}, we saved your setup — reactivate anytime`;
  const body = `
<h2 style="margin:0 0 16px;color:#111827;font-size:22px;font-weight:600;">Your setup is safe</h2>
<p style="margin:0 0 16px;color:#6b7280;font-size:16px;line-height:24px;">
  Your LLMHosts trial has ended, but all your devices, API keys, and configuration are preserved.
  Reactivate anytime to pick up exactly where you left off.
</p>
<p style="margin:0 0 16px;color:#6b7280;font-size:14px;">
  If cost was a concern, remember: LLMHosts Pro pays for itself if you spend more than $50/month
  on AI APIs. The average user saves 35%.
</p>
${ctaButton(pricingUrl, 'Reactivate Your Plan')}
<p style="margin:24px 0 0;color:#9ca3af;font-size:13px;">If you have feedback on why you didn't continue, reply to this email. It helps us improve.</p>`;
  const text = `Hi ${name}, your trial ended but your setup is saved.\n\nReactivate anytime: ${pricingUrl}\n\nFeedback? Reply to this email.`;
  return sendEmail(email, subject, emailWrapper(subject, body), text);
}

// ---------------------------------------------------------------------------
// Dunning — Payment failed recovery
// ---------------------------------------------------------------------------
export async function sendDunningEmail(
  email: string,
  name: string,
  attemptCount: number,
): Promise<SendResult> {
  const billingUrl = `${BASE_URL}/dashboard/settings?tab=billing`;

  const urgency = attemptCount >= 3
    ? 'Your account will be downgraded soon if payment is not resolved.'
    : 'Please update your payment method to avoid any interruption.';

  const subject = attemptCount >= 3
    ? `Urgent: Your LLMHosts payment has failed ${attemptCount} times`
    : 'Action needed: Your LLMHosts payment failed';

  const body = `
<h2 style="margin:0 0 16px;color:#111827;font-size:22px;font-weight:600;">Payment failed</h2>
<p style="margin:0 0 16px;color:#6b7280;font-size:16px;line-height:24px;">
  We couldn't process your latest payment. ${urgency}
</p>
<p style="margin:0 0 16px;color:#6b7280;font-size:14px;">
  Updating your card takes less than a minute and ensures uninterrupted access to your
  devices and API keys.
</p>
${ctaButton(billingUrl, 'Update Payment Method')}
<p style="margin:24px 0 0;color:#9ca3af;font-size:13px;">If you believe this is an error, reply to this email and we'll help resolve it.</p>`;
  const text = `Hi ${name ?? 'there'}, we couldn't process your payment. ${urgency}\n\nUpdate your payment method: ${billingUrl}`;
  return sendEmail(email, subject, emailWrapper(subject, body), text);
}

// ---------------------------------------------------------------------------
// Subscription cancelled — recovery offer
// ---------------------------------------------------------------------------
export async function sendSubscriptionCancelledRecovery(
  email: string,
  name: string,
): Promise<SendResult> {
  const pricingUrl = `${BASE_URL}/pricing`;
  const subject = `${name ?? 'Hey'}, your LLMHosts subscription has ended`;

  const body = `
<h2 style="margin:0 0 16px;color:#111827;font-size:22px;font-weight:600;">We're sorry to see you go</h2>
<p style="margin:0 0 16px;color:#6b7280;font-size:16px;line-height:24px;">
  Your subscription has been cancelled. Your devices and API keys are preserved on the Free plan,
  but Pro features are no longer available.
</p>
<p style="margin:0 0 16px;color:#6b7280;font-size:14px;">
  If you change your mind, you can resubscribe at any time and pick up where you left off —
  no reconfiguration needed.
</p>
${ctaButton(pricingUrl, 'View Plans')}
<p style="margin:24px 0 0;color:#9ca3af;font-size:13px;">We'd love to know what we could improve. Reply to this email with your feedback.</p>`;
  const text = `Hi ${name ?? 'there'}, your subscription has been cancelled.\n\nYour setup is preserved. Resubscribe anytime: ${pricingUrl}\n\nFeedback? Reply to this email.`;
  return sendEmail(email, subject, emailWrapper(subject, body), text);
}
