import { NextRequest, NextResponse } from "next/server"; import { cookies } from "next/headers"; import { directusFetch } from "@/lib/directus"; // Change these if your collection/owner field differ const BASE_COLLECTION = process.env.RIGS_COLLECTION || "rigs"; const OWNER_FIELD = process.env.RIGS_OWNER_FIELD || "owner"; // Pull the user's Directus access token from cookies (await to satisfy Next 15 typings) async function bearerFromCookies() { const jar = await cookies(); const at = jar.get("ma_at")?.value; if (!at) throw new Error("Not authenticated"); return `Bearer ${at}`; } // Resolve current Directus user id using their access token async function getMeId(auth: string): Promise { const res = await directusFetch<{ data: { id: string } }>( `/users/me?fields=id`, { headers: { Authorization: auth } } ); const id = res?.data?.id; if (!id) throw new Error("Unable to resolve current user id"); return id; } // List rigs that belong to the current user export async function GET(_req: NextRequest) { try { const auth = await bearerFromCookies(); const meId = await getMeId(auth); const { data } = await directusFetch<{ data: any[] }>( `/items/${BASE_COLLECTION}?filter[${OWNER_FIELD}][_eq]=${encodeURIComponent( meId )}&limit=200&sort=-date_created`, { headers: { Authorization: auth } } ); return NextResponse.json({ ok: true, data }); } catch (err: any) { return NextResponse.json( { error: err?.message || "List failed" }, { status: 401 } ); } } // Create a new rig for the current user export async function POST(req: NextRequest) { try { const auth = await bearerFromCookies(); const meId = await getMeId(auth); const body = await req.json(); // Ensure ownership is set to the current user const payload = { ...body, [OWNER_FIELD]: meId }; const { data } = await directusFetch<{ data: any }>( `/items/${BASE_COLLECTION}`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: auth, }, body: JSON.stringify(payload), } ); return NextResponse.json({ ok: true, data }); } catch (err: any) { return NextResponse.json( { error: err?.message || "Create failed" }, { status: 400 } ); } }