/**
 * POST /api/brands/[brandId]/seo-audit/notify-complete
 *
 * Creates an in-app notification for the brand when an SEO audit
 * completes. Called client-side when the polling loop detects
 * status === "completed" — lets the notification bell surface the
 * result even after the user navigates away from /technical-audit.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export async function POST(
  _req: Request,
  { params }: { params: Promise<{ brandId: string }> },
) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { brandId } = await params;

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

  await prisma.notification.create({
    data: {
      brandId,
      title: "SEO Audit Complete",
      message: `Your site audit for ${brand.domain ?? brand.name} has finished. View the updated findings on the Technical Audit page.`,
      type: "audit_complete",
      severity: "medium",
      channel: "in_app",
      metadata: { link: "/technical-audit" },
    },
  });

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