/**
 * GET /api/integrations/nango-status?brandId=…
 * Returns connection status for all Nango-managed integrations.
 */

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

export const dynamic = "force-dynamic";

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

  const brandId = new URL(req.url).searchParams.get("brandId");
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  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 });
  }

  if (!isNangoConfigured()) {
    return NextResponse.json({ configured: false, integrations: {} });
  }

  const connections = await listNangoConnections(brandId);
  const connectedProviders = new Set(connections.map((c) => c.provider_config_key));

  const integrations: Record<string, "connected" | "disconnected" | "not_available"> = {};
  for (const [label, provider] of Object.entries(NANGO_PROVIDERS)) {
    integrations[label] = connectedProviders.has(provider) ? "connected" : "disconnected";
  }

  return NextResponse.json({
    configured: true,
    integrations,
    connections: connections.map((c) => ({
      provider: c.provider_config_key,
      createdAt: c.created,
    })),
  });
}
