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

// GET /api/organizations — list orgs the user belongs to
export const dynamic = "force-dynamic";

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

  const orgs = await prisma.organization.findMany({
    where: {
      memberships: { some: { userId: user.id } },
    },
    include: {
      brands: { select: { id: true, name: true, domain: true, status: true } },
      memberships: { select: { id: true, role: true, user: { select: { id: true, name: true, email: true } } } },
    },
  });

  return NextResponse.json(orgs);
}

// POST /api/organizations — create a new org + make user the owner
export async function POST(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  try {
    const { name } = await req.json();

    if (!name?.trim()) {
      return NextResponse.json({ error: "Organization name is required" }, { status: 400 });
    }

    // Create slug from name
    const slug = name.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");

    // Check if slug exists
    const existing = await prisma.organization.findUnique({ where: { slug } });
    if (existing) {
      return NextResponse.json({ error: "Organization name already taken" }, { status: 400 });
    }

    const org = await prisma.organization.create({
      data: {
        name: name.trim(),
        slug,
        memberships: {
          create: { userId: user.id, role: "owner" },
        },
      },
      include: {
        memberships: { select: { id: true, role: true, user: { select: { id: true, name: true, email: true } } } },
      },
    });

    return NextResponse.json(org, { status: 201 });
  } catch {
    return NextResponse.json({ error: "Something went wrong" }, { status: 500 });
  }
}
