// app/api/staff/organizations/create/route.ts
import { NextResponse } from "next/server";
import { cookies, headers } from "next/headers";
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
import { createClient } from "@supabase/supabase-js";

// Helper pour slugifier le nom du client
function slugify(text: string): string {
  return text
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '') // Enlever les accents
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9]+/g, '-') // Remplacer les caractères spéciaux par des tirets
    .replace(/^-+|-+$/g, ''); // Enlever les tirets en début/fin
}

export async function POST(req: Request) {
  try {
    const sb = createRouteHandlerClient({ cookies });
    const { data: { user } } = await sb.auth.getUser();
    if (!user) return new NextResponse("Unauthorized", { status: 401 });

    const { data: me } = await sb
      .from("staff_users")
      .select("is_staff")
      .eq("user_id", user.id)
      .maybeSingle();
    if (!me?.is_staff) return new NextResponse("Forbidden", { status: 403 });

    const form = await req.formData();
    const name = String(form.get("name") || "").trim();

    if (!name) return NextResponse.json({ error: "missing_name" }, { status: 400 });

    const admin = createClient(
      process.env.NEXT_PUBLIC_SUPABASE_URL!,
      process.env.SUPABASE_SERVICE_ROLE_KEY!,
      { auth: { autoRefreshToken: false, persistSession: false } }
    );

    // Créer automatiquement structure_api et documents_slug à partir du name
    const payload: Record<string, any> = { 
      name,
      structure_api: name, // Toujours le nom complet
      documents_slug: slugify(name) // Version slugifiée pour les documents
    };

    const { data, error } = await admin
      .from("organizations")
      .insert(payload)
      .select("id")
      .maybeSingle();

    if (error) return NextResponse.json({ error: error.message }, { status: 400 });

    const accept = headers().get("accept") || "";
    if (accept.includes("text/html")) {
      return NextResponse.redirect(new URL("/staff/utilisateurs", req.url), { status: 303 });
    }

    return NextResponse.json({ ok: true, id: data?.id });
  } catch (e: any) {
    return new NextResponse(e?.message || "Internal Server Error", { status: 500 });
  }
}
