import { NextResponse } from "next/server";
import { DepartmentKey } from "@prisma/client";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { canManageMarketing } from "@/lib/marketing/persistence";

export async function POST() {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  if (!canManageMarketing(session.user.role, session.user.department)) {
    return NextResponse.json({ error: "Only owner/marketing leader can disconnect Meta." }, { status: 403 });
  }

  await prisma.$transaction(async (tx) => {
    await tx.marketingMetaConnection.deleteMany({
      where: {
        department: DepartmentKey.marketing,
        isActive: false,
      },
    });
    await tx.marketingMetaConnection.updateMany({
      where: {
        department: DepartmentKey.marketing,
        isActive: true,
      },
      data: { isActive: false },
    });
  });

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