import { createAdminClient } from '@/lib/supabase/admin';
import { NextRequest, NextResponse } from 'next/server';
import nodemailer from 'nodemailer';

export const runtime = 'nodejs';

// Public newsletter subscribe endpoint. Used by:
//   - NewsletterModal (site-wide popup)
//   - Header subscribe widget
//   - Homepage NewsletterSignup section
//   - Footer signup
//
// Why service-role (not the session client):
//   bb.newsletter_subscribers' RLS only has an INSERT policy for anon
//   ('public_subscribe_newsletter') — upsert needs both INSERT+UPDATE
//   to handle re-subscribers. Service-role bypasses RLS cleanly.

export async function POST(req: NextRequest) {
  try {
    const { email, topics, source } = await req.json();

    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      return NextResponse.json({ error: 'Please enter a valid email address.' }, { status: 400 });
    }

    const normalized = email.toLowerCase().trim();
    const supabase = createAdminClient();

    // Upsert subscriber (re-subscribe if previously unsubscribed)
    const { error } = await supabase
      .from('newsletter_subscribers')
      .upsert(
        {
          email: normalized,
          topics: topics && Array.isArray(topics) ? topics : [],
          status: 'active',
          subscribed_at: new Date().toISOString(),
          unsubscribed_at: null,
        },
        { onConflict: 'email' },
      );

    if (error) {
      console.error('newsletter_subscribers upsert failed:', error.message, error.details);
      return NextResponse.json(
        { error: 'Could not save subscription. Please try again in a moment.' },
        { status: 500 },
      );
    }

    // Best-effort welcome email — never block the API response on SMTP.
    // The signup is already saved to the DB, so we return 200 either way
    // and let the email fire in the background.
    void sendWelcome(normalized, topics).catch((e) =>
      console.error('newsletter welcome email failed:', e?.message || e),
    );

    return NextResponse.json({ success: true, source: source || null });
  } catch (err: any) {
    console.error('Subscribe handler error:', err?.message || err);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}

async function sendWelcome(email: string, topics?: string[]) {
  const smtpHost = process.env.SMTP_HOST;
  const smtpPort = parseInt(process.env.SMTP_PORT || '587', 10);
  const smtpUser = process.env.SMTP_USER;
  const smtpPass = process.env.SMTP_PASS;
  const fromEmail = process.env.SMTP_FROM_EMAIL || smtpUser;
  const fromName = process.env.SMTP_FROM_NAME || 'AV Beat';
  const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://avbeat.com';

  if (!smtpHost || !smtpUser || !smtpPass || !fromEmail) {
    // SMTP not configured — signal that to logs but don't blow up.
    console.warn('newsletter welcome: SMTP env not set; skipping send');
    return;
  }

  const transporter = nodemailer.createTransport({
    host: smtpHost,
    port: smtpPort,
    secure: smtpPort === 465,
    auth: { user: smtpUser, pass: smtpPass },
  });

  const topicsBlock =
    topics && topics.length > 0
      ? `<p style="color:#aaa;font-size:14px;line-height:1.5;margin:14px 0 0;">You'll receive coverage on: <strong style="color:#1D4ED8;">${topics.join(', ')}</strong></p>`
      : '';

  await transporter.sendMail({
    from: `"${fromName}" <${fromEmail}>`,
    to: email,
    subject: 'Welcome to AV Beat',
    html: `
<!DOCTYPE html>
<html><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width,initial-scale=1" /><title>Welcome to AV Beat</title></head>
<body style="margin:0;padding:0;background:#F8FAFC;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif;">
<table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="background:#F8FAFC;padding:40px 16px;">
  <tr><td align="center">
    <table role="presentation" cellpadding="0" cellspacing="0" width="600" style="max-width:600px;background:#FFFFFF;border:1px solid #DCE6F2;border-radius:10px;overflow:hidden;">
      <tr><td style="padding:32px 36px 8px;">
        <div style="font-family:'Courier New',monospace;font-size:10px;font-weight:700;letter-spacing:0.22em;text-transform:uppercase;color:#1D4ED8;">AV Beat Newsletter</div>
        <h1 style="margin:14px 0 8px;font-size:24px;line-height:1.2;color:#ffffff;font-weight:800;">You're in</h1>
        <p style="margin:0;color:#0F172A;font-size:15px;line-height:1.55;">Thanks for subscribing to <strong style="color:#ffffff;">AV Beat</strong> — the digital platform for pro AV, live production, and display tech professionals.</p>
        ${topicsBlock}
      </td></tr>
      <tr><td style="padding:18px 36px 8px;">
        <p style="margin:0;color:#475569;font-size:14px;line-height:1.6;">You'll get one editorial dispatch a week — industry news, product launches, InfoComm/ISE coverage, and deep-dives. No spam, no sales calls.</p>
      </td></tr>
      <tr><td style="padding:18px 36px 26px;" align="center">
        <a href="${siteUrl}/news" style="display:inline-block;background:#1D4ED8;color:#ffffff;text-decoration:none;padding:11px 22px;border-radius:6px;font-weight:700;font-size:13px;letter-spacing:0.05em;text-transform:uppercase;">Browse AV Industry News</a>
      </td></tr>
      <tr><td style="padding:18px 36px 28px;border-top:1px solid #DCE6F2;">
        <p style="margin:0;color:#8a7e6e;font-size:11px;line-height:1.5;">You're receiving this because you signed up at <a href="${siteUrl}" style="color:#1D4ED8;text-decoration:none;">avbeat.com</a>. <a href="${siteUrl}/unsubscribe?email=${encodeURIComponent(email)}" style="color:#475569;">Unsubscribe anytime</a>.</p>
      </td></tr>
    </table>
  </td></tr>
</table>
</body></html>`,
  });
}
