/**
 * POST /api/integrations/nango-disconnect
 * Body: { brandId, provider }
 * Disconnects a Nango-managed integration.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { deleteNangoConnection, NANGO_PROVIDERS } from "@/lib/integrations/nango";

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 { brandId?: string; provider?: string } | null;
  if (!body?.brandId || !body?.provider) {
    return NextResponse.json({ error: "brandId and provider required" }, { status: 400 });
  }

  const brand = await prisma.brand.findUnique({
    where: { id: body.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 });
  }

  const providerKey = NANGO_PROVIDERS[body.provider] ?? body.provider;
  const success = await deleteNangoConnection(providerKey, body.brandId);

  return NextResponse.json({ success });
}
