// app/api/my/rigs/route.ts import { NextRequest, NextResponse } from "next/server"; import { cookies } from "next/headers"; const BASE = process.env.DIRECTUS_URL!; function bearerFromCookies() { const store = cookies(); const at = store.get("ma_at")?.value; if (!at) throw new Error("Not authenticated"); return `Bearer ${at}`; } async function fetchJSON(path: string, init: RequestInit = {}) { const res = await fetch(`${BASE}${path}`, init); const text = await res.text(); let json: any = null; try { json = text ? JSON.parse(text) : null; } catch {} if (!res.ok) { throw new Error( `Directus error ${res.status}: ${text || res.statusText}` ); } return json ?? {}; } export async function GET() { try { const auth = bearerFromCookies(); // Your Users role already restricts READ to owner == $CURRENT_USER const out = await fetchJSON(`/items/user_rigs?fields=*,owner.username`, { headers: { Authorization: auth, Accept: "application/json" }, }); return NextResponse.json(out); } catch (e: any) { return NextResponse.json({ error: e.message || String(e) }, { status: 401 }); } } export async function POST(req: NextRequest) { const started = Date.now(); try { const auth = bearerFromCookies(); const body = await req.json(); // minimal validation – keep it light, let Directus enforce the rest const name = String(body?.name ?? "").trim(); const rig_type = String(body?.rig_type ?? "").trim(); if (!name) return NextResponse.json({ error: "name is required" }, { status: 400 }); if (!rig_type) return NextResponse.json({ error: "rig_type is required" }, { status: 400 }); // Get the current user's id so we can set owner explicitly const me = await fetchJSON(`/users/me`, { headers: { Authorization: auth, Accept: "application/json" }, }); const ownerId = me?.data?.id; if (!ownerId) throw new Error("Could not resolve current user id"); const payload = { name, rig_type, owner: ownerId, // pass through optional relational fields only if present (prevents FK violations) laser_source: body?.laser_source ?? null, laser_focus_lens: body?.laser_focus_lens ?? null, laser_scan_lens: body?.laser_scan_lens ?? null, laser_scan_lens_apt: body?.laser_scan_lens_apt ?? null, laser_scan_lens_exp: body?.laser_scan_lens_exp ?? null, laser_software: body?.laser_software ?? null, notes: body?.notes ?? null, }; const created = await fetchJSON(`/items/user_rigs`, { method: "POST", headers: { Authorization: auth, Accept: "application/json", "Content-Type": "application/json", Prefer: "return=representation", }, body: JSON.stringify(payload), }); return NextResponse.json(created); } catch (e: any) { return NextResponse.json( { error: e?.message || "Failed to create rig" }, { status: 400 } ); } finally { const ms = Date.now() - started; if (ms) console.log(`[my/rigs POST] in ~${ms}ms`); } }