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

function slugify(name: string): string {
  return name
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/(^-|-$)/g, "")
    .slice(0, 48);
}

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

  const user = await prisma.user.findUnique({
    where: { id: session.user.id },
    select: { displayName: true, email: true },
  });

  const displayName = user?.displayName || user?.email?.split("@")[0] || "User";
  const orgName = `${displayName}'s Workspace`;
  const baseSlug = slugify(orgName);
  const slug = `${baseSlug}-${session.user.id.slice(0, 6)}`;

  const org = await prisma.organization.create({
    data: {
      name: orgName,
      slug,
      type: "personal",
      onboardingComplete: true,
      onboardingStep: 99,
    },
  });

  await prisma.orgMember.create({
    data: {
      userId: session.user.id,
      organizationId: org.id,
      role: "owner",
    },
  });

  await prisma.user.update({
    where: { id: session.user.id },
    data: { activeOrgId: org.id },
  });

  return NextResponse.json({ success: true, orgId: org.id });
}
