// app/rigs/RigBuilderServer.tsx
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import RigBuilderClient from "./RigBuilderClient";

type Opt = { id: string | number; label: string };

export default async function RigBuilderServer() {
    const jar = await cookies(); // <-- await in Next 15
    const ma_at = jar.get("ma_at")?.value;
    if (!ma_at) {
        const next = encodeURIComponent("/rigs");
        redirect(`/auth/sign-in?next=${next}`);
    }

    const DIRECTUS = (process.env.DIRECTUS_URL || "").replace(/\/$/, "");
    const res = await fetch(
        `${DIRECTUS}/items/user_rig_type?fields=id,name&sort=sort`,
        {
            headers: {
                Authorization: `Bearer ${ma_at}`,
                Accept: "application/json",
                "Cache-Control": "no-store",
            },
            cache: "no-store",
        }
    );

    if (!res.ok) {
        const text = await res.text().catch(() => "");
        throw new Error(
            `Failed to load user_rig_type (${res.status}): ${text || res.statusText}`
        );
    }

    const json = await res.json().catch(() => ({ data: [] as any[] }));
    const rigTypes: Opt[] = (json?.data ?? []).map((r: any) => ({
        id: r.id,
        label: r.name ?? String(r.id),
    }));

    return <RigBuilderClient rigTypes={rigTypes} />;
}
