/**
 * POST /api/client-portal/setup — create/update portal config.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { buildDefaultConfig, enabledPageIds, type PortalConfig } from "@/lib/portal-config";

export const dynamic = "force-dynamic";

export async function POST(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const body = await req.json().catch(() => null) as Record<string, unknown> | null;
  if (!body?.brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  const brandId = String(body.brandId);
  const brand = await prisma.brand.findUnique({
    where: { id: brandId },
    include: { organization: { include: { memberships: true } } },
  });
  if (!brand) return NextResponse.json({ error: "Brand not found" }, { status: 404 });
  if (!brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  // Custom-domain handling: if the agency changes the custom domain,
  // reset the verification state so they re-verify. Treat an empty
  // string as "clear the custom domain" so the field can be removed
  // from the UI without a dedicated "unset" button.
  const existingPortal = await prisma.clientPortal.findUnique({
    where: { brandId },
    select: { customDomain: true, customDomainStatus: true },
  });
  const nextCustomDomain = typeof body.customDomain === "string"
    ? body.customDomain.trim().toLowerCase() || null
    : undefined;
  const customDomainChanged =
    nextCustomDomain !== undefined &&
    nextCustomDomain !== (existingPortal?.customDomain ?? null);

  const data = {
    isEnabled: body.isEnabled !== false,
    agencyName: typeof body.agencyName === "string" ? body.agencyName : undefined,
    agencyLogo: typeof body.agencyLogo === "string" ? body.agencyLogo : undefined,
    agencyFavicon: typeof body.agencyFavicon === "string" ? body.agencyFavicon : undefined,
    primaryColor: typeof body.primaryColor === "string" ? body.primaryColor : undefined,
    accentColor: typeof body.accentColor === "string" ? body.accentColor : undefined,
    // Custom domain + white-label email fields
    ...(nextCustomDomain !== undefined ? { customDomain: nextCustomDomain } : {}),
    ...(customDomainChanged ? {
      // Changing the domain invalidates the previous verification.
      // Null DNS target lets the UI prompt for re-verification.
      customDomainStatus: nextCustomDomain ? "pending" : null,
      customDomainVerifiedAt: null,
    } : {}),
    replyToEmail: typeof body.replyToEmail === "string" ? body.replyToEmail.trim() || null : undefined,
    supportEmail: typeof body.supportEmail === "string" ? body.supportEmail.trim() || null : undefined,
    portalConfig: (body.portalConfig && typeof body.portalConfig === "object"
      ? body.portalConfig
      : buildDefaultConfig()) as object,
    // Derive allowedPages from portalConfig for backward compat
    allowedPages: body.portalConfig
      ? enabledPageIds(body.portalConfig as PortalConfig)
      : Array.isArray(body.allowedPages) ? (body.allowedPages as string[]) : enabledPageIds(buildDefaultConfig()),
    hideSourceBranding: body.hideSourceBranding !== false,
  };

  const portal = await prisma.clientPortal.upsert({
    where: { brandId },
    create: { brandId, ...data },
    update: data,
  });

  return NextResponse.json({ portal });
}
