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

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

  const memberships = await prisma.orgMember.findMany({
    where: { userId: session.user.id },
    include: {
      organization: {
        select: {
          id: true,
          name: true,
          slug: true,
          type: true,
          onboardingComplete: true,
        },
      },
    },
    orderBy: { createdAt: "asc" },
  });

  const orgs = memberships.map((m) => ({
    id: m.organization.id,
    name: m.organization.name,
    slug: m.organization.slug,
    type: m.organization.type,
    role: m.role,
    onboardingComplete: m.organization.onboardingComplete,
  }));

  return NextResponse.json({ orgs, activeOrgId: session.user.orgId });
}
