import { NextRequest, NextResponse } from "next/server";
import { Resend } from "resend";
import { newsletterUserTemplate } from "@/lib/emails/newsletterUserTemplate";
import { newsletterAdminTemplate } from "@/lib/emails/newsletterAdminTemplate";

const resend = new Resend(process.env.RESEND_API_KEY);

// Verified-domain sender. Defaults in code so a missing env var can never
// silently break delivery (RESEND_FROM_EMAIL was unset on the server, which
// is what caused every send to fail with `from: "DesignShare <undefined>"`).
const FROM = `DesignShare <${process.env.RESEND_FROM_EMAIL || "noreply@designshare.net"}>`;
const ADMIN = process.env.NEWSLETTER_ADMIN_EMAIL || "info@designshare.net";

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

// --- Basic in-memory rate limiting (per server process / PM2 instance) ---
const RATE_LIMIT = 5; // max submissions
const RATE_WINDOW_MS = 10 * 60 * 1000; // per 10 minutes, per IP
const hits = new Map<string, number[]>();

function rateLimited(ip: string): boolean {
  const now = Date.now();
  const recent = (hits.get(ip) || []).filter((t) => now - t < RATE_WINDOW_MS);
  recent.push(now);
  hits.set(ip, recent);
  // Opportunistic cleanup so the map doesn't grow unbounded.
  if (hits.size > 5000) {
    for (const [key, times] of hits) {
      if (times.every((t) => now - t >= RATE_WINDOW_MS)) hits.delete(key);
    }
  }
  return recent.length > RATE_LIMIT;
}

function getIp(req: NextRequest): string {
  const xff = req.headers.get("x-forwarded-for");
  if (xff) return xff.split(",")[0].trim();
  return req.headers.get("x-real-ip") || "unknown";
}

export async function POST(req: NextRequest) {
  let body: { email?: string; company?: string };
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: "Invalid request." }, { status: 400 });
  }

  const email = (body.email || "").trim().toLowerCase();
  const honeypot = body.company; // hidden field — humans never fill it

  // Honeypot: pretend success, send nothing. Don't tip off the bot.
  if (honeypot) {
    return NextResponse.json({ ok: true });
  }

  if (!email || !EMAIL_RE.test(email) || email.length > 254) {
    return NextResponse.json(
      { error: "Please enter a valid email address." },
      { status: 400 },
    );
  }

  if (rateLimited(getIp(req))) {
    return NextResponse.json(
      { error: "Too many requests. Please try again in a few minutes." },
      { status: 429 },
    );
  }

  // Notify the team — this is the deliverable that must reach info@designshare.net.
  const { data: adminData, error: adminError } = await resend.emails.send({
    from: FROM,
    to: ADMIN,
    replyTo: email,
    subject: `New subscriber: ${email}`,
    html: newsletterAdminTemplate(email),
  });

  if (adminError) {
    console.error("[newsletter] Resend admin send failed:", adminError);
    return NextResponse.json(
      { error: "Subscription failed. Please try again." },
      { status: 502 },
    );
  }

  console.log("[newsletter] admin notification sent:", adminData?.id, email);

  // Welcome email to the subscriber — best effort, must not fail the request.
  const { error: userError } = await resend.emails.send({
    from: FROM,
    to: email,
    subject: "You're on the list — The DesignShare Dispatch",
    html: newsletterUserTemplate(email),
  });
  if (userError) {
    console.error("[newsletter] welcome email failed (non-fatal):", userError);
  }

  return NextResponse.json({ ok: true });
}
