import { NextRequest, NextResponse } from 'next/server';
import nodemailer from 'nodemailer';

export async function POST(request: NextRequest) {
  try {
    const { companies, count, email } = await request.json();
    const transport = nodemailer.createTransport({
      host: process.env.SMTP_HOST,
      port: parseInt(process.env.SMTP_PORT || '587'),
      secure: false,
      auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS },
    });
    const companyList = (companies || []).slice(0, 10).map((c: string) => `<li>${c}</li>`).join('');
    const moreText = companies?.length > 10 ? `<p style="color:#888;font-size:13px;">...and ${companies.length - 10} more</p>` : '';
    await transport.sendMail({
      from: `"${process.env.SMTP_FROM_NAME || 'AV Beat'}" <${process.env.SMTP_FROM_EMAIL}>`,
      to: email || 'ryan.salazar@relevantmediaproperties.com',
      subject: `[Relevant Media Properties] ${count} new company story suggestion${count !== 1 ? 's' : ''} queued`,
      html: `
        <div style="font-family:Arial,sans-serif;max-width:600px;background:#0a0a0a;color:#e5e5e5;padding:32px;border-radius:8px;">
          <div style="margin-bottom:24px;">
            <h1 style="color:#1D4ED8;font-size:20px;margin:0 0 4px;">Relevant Media Properties</h1>
            <p style="color:#555;font-size:12px;margin:0;">AV Beat · AV Beat — Company Story Engine</p>
          </div>
          <h2 style="font-size:18px;color:#fff;margin:0 0 12px;">New Company Stories Queued for Review</h2>
          <p style="color:#aaa;font-size:14px;line-height:1.6;margin:0 0 20px;">
            The automated company story engine has queued <strong style="color:#fff;">${count} new AI-drafted story suggestion${count !== 1 ? 's' : ''}</strong> based on company mentions in recently published articles.
          </p>
          <div style="background:#111;border:1px solid #252525;border-radius:6px;padding:16px;margin-bottom:24px;">
            <p style="color:#888;font-size:12px;font-weight:bold;text-transform:uppercase;letter-spacing:0.05em;margin:0 0 10px;">Companies Detected</p>
            <ul style="margin:0;padding-left:20px;color:#e5e5e5;font-size:14px;line-height:1.8;">${companyList}</ul>
            ${moreText}
          </div>
          <a href="${process.env.NEXT_PUBLIC_SITE_URL || 'https://avbeat.com'}/admin/company-tracker"
             style="display:inline-block;background:#1D4ED8;color:#fff;text-decoration:none;padding:10px 20px;border-radius:6px;font-size:14px;font-weight:bold;">
            Review Story Queue →
          </a>
          <p style="color:#444;font-size:12px;margin-top:24px;">
            Manage settings at <a href="${process.env.NEXT_PUBLIC_SITE_URL || 'https://avbeat.com'}/admin/company-tracker" style="color:#1D4ED8;">Company Tracker</a>
          </p>
        </div>
      `,
    });
    return NextResponse.json({ success: true });
  } catch {
    return NextResponse.json({ success: false });
  }
}
