/**
 * POST /api/client-portal/auth/send-magic-link
 * Generates a single-use token, stores it on ClientUser, and sends
 * a branded magic link email.
 */

import { NextResponse } from "next/server";
import { randomUUID } from "crypto";
import { prisma } from "@/lib/prisma";
import { sendEmail } from "@/lib/services/email-sender";

export const dynamic = "force-dynamic";

const APP_URL = process.env.NEXT_PUBLIC_APP_URL || "https://app.meseo.io";

/** Build the base URL for magic-link verification. Uses the agency's
 *  verified custom domain when available, otherwise falls back to the
 *  platform APP_URL. Keeps invite links on-brand for agencies that
 *  have wired up a white-label domain. */
function resolveBaseUrl(portal: {
  customDomain: string | null;
  customDomainStatus: string | null;
}): string {
  if (portal.customDomain && portal.customDomainStatus === "verified") {
    return `https://${portal.customDomain}`;
  }
  return APP_URL;
}

export async function POST(req: Request) {
  const body = await req.json().catch(() => null) as { email?: string; brandId?: string } | null;
  if (!body?.email || !body?.brandId) {
    return NextResponse.json({ error: "email and brandId required" }, { status: 400 });
  }

  const portal = await prisma.clientPortal.findUnique({ where: { brandId: body.brandId } });
  if (!portal || !portal.isEnabled) {
    return NextResponse.json({ error: "Portal not found or disabled" }, { status: 404 });
  }

  const user = await prisma.clientUser.findUnique({
    where: { portalId_email: { portalId: portal.id, email: body.email.toLowerCase() } },
  });
  if (!user || !user.isActive) {
    // Don't reveal whether the email exists — always return success
    return NextResponse.json({ success: true });
  }

  const token = randomUUID();
  const tokenExpiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000);
  await prisma.clientUser.update({
    where: { id: user.id },
    data: { accessToken: token, tokenExpiresAt },
  });

  const baseUrl = resolveBaseUrl(portal);
  const link = `${baseUrl}/api/client-portal/auth/verify?token=${token}`;
  const agencyName = portal.agencyName || "Your Agency";
  const brandColor = portal.primaryColor || "#EF4444";
  // Footer identity: support email first, then reply-to, then nothing.
  const contactEmail = portal.supportEmail || portal.replyToEmail || null;

  const html = `<!DOCTYPE html><html><body style="margin:0;padding:0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;background:#f1f5f9">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tr><td align="center" style="padding:40px 16px">
<table role="presentation" width="480" cellpadding="0" cellspacing="0" style="background:#fff;border-radius:12px;overflow:hidden;max-width:480px;width:100%">
<tr><td style="background:${brandColor};padding:24px;text-align:center">
${portal.agencyLogo ? `<img src="${portal.agencyLogo}" alt="${agencyName}" style="max-height:40px;max-width:160px;margin-bottom:8px" />` : ""}
<h1 style="margin:0;font-size:18px;font-weight:700;color:#fff">${agencyName}</h1>
</td></tr>
<tr><td style="padding:32px 24px;text-align:center">
<p style="margin:0 0 8px;font-size:16px;font-weight:600;color:#0f172a">Your SEO Dashboard is Ready</p>
<p style="margin:0 0 20px;font-size:14px;color:#334155">Click below to access your dashboard:</p>
<a href="${link}" style="display:inline-block;padding:14px 32px;background:${brandColor};color:#fff;font-weight:700;font-size:14px;border-radius:8px;text-decoration:none">Sign In</a>
<p style="margin:24px 0 0;font-size:12px;color:#94a3b8">This link expires in 24 hours and can only be used once.</p>
</td></tr>
${contactEmail ? `<tr><td style="padding:12px 24px;border-top:1px solid #e2e8f0;background:#f8fafc;text-align:center">
<p style="margin:0;font-size:11px;color:#64748b">Need help? Contact <a href="mailto:${contactEmail}" style="color:${brandColor};font-weight:600;text-decoration:none">${contactEmail}</a></p>
</td></tr>` : ""}
${!portal.hideSourceBranding ? `<tr><td style="padding:10px;background:#f8fafc;text-align:center">
<p style="margin:0;font-size:10px;color:#94a3b8">Powered by meSEO</p>
</td></tr>` : ""}
</table>
</td></tr></table></body></html>`;

  // White-label envelope: From display name = agency, reply-to routes
  // client replies to the agency inbox when they've configured one.
  // Subject uses the agency name so clients recognise the sender in
  // their inbox preview.
  await sendEmail(
    [user.email],
    `${agencyName} — Your SEO Dashboard is Ready`,
    html,
    {
      fromName: agencyName,
      ...(portal.replyToEmail ? { replyTo: portal.replyToEmail } : {}),
    },
  );
  return NextResponse.json({ success: true });
}
