// 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";

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();
    const structure_api = String(form.get("structure_api") || "").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 } }
    );

    // Insère uniquement les colonnes existantes dans la table `organizations`
    // Schéma actuel: id, name, structure_api, created_at
    const payload: Record<string, any> = { name };
    if (structure_api) payload.structure_api = structure_api;

    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 });
  }
}
