import { NextResponse } from "next/server";
import { describeTenantSite } from "@/core/config/domains";
import { registerSchema } from "@/core/validation/schemas";
import { registerStudio } from "@/services/tenant-service";

export async function POST(request: Request) {
  let body: unknown;
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
  }

  const parsed = registerSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json(
      { error: "Validation failed", details: parsed.error.flatten() },
      { status: 400 },
    );
  }

  try {
    const result = await registerStudio(parsed.data);
    const requestHost =
      request.headers.get("x-archi-hostname") ??
      request.headers.get("host") ??
      null;
    const site = describeTenantSite(result.tenant.slug, { requestHost });
    return NextResponse.json(
      {
        userId: result.user.id,
        tenantId: result.tenant.id,
        slug: result.tenant.slug,
        site: site.url,
        siteHost: site.host,
        canonicalHost: site.canonicalHost,
        environment: site.environment,
      },
      { status: 201 },
    );
  } catch (error) {
    const err = error as { name?: string; message?: string; alternatives?: string[] };
    if (err.name === "ConflictError") {
      return NextResponse.json({ error: err.message }, { status: 409 });
    }
    if (err.name === "SlugConflictError") {
      return NextResponse.json(
        { error: err.message, alternatives: err.alternatives ?? [] },
        { status: 409 },
      );
    }
    console.error("Registration failed", error);
    return NextResponse.json({ error: "Registration failed" }, { status: 500 });
  }
}
