// app/api/options/lens/route.ts export const dynamic = "force-dynamic"; import { NextRequest, NextResponse } from "next/server"; const BASE = (process.env.DIRECTUS_URL || "").replace(/\/$/, ""); function buildPath(target?: string | null) { // Adjust the collection name if yours differs (e.g., laser_scan_lens) const url = new URL(`${BASE}/items/laser_scan_lens`); url.searchParams.set("fields", "id,name"); url.searchParams.set("sort", "name"); // Example if you model per-target lenses: // if (target) url.searchParams.set("filter[target][_eq]", target); return String(url); } async function dFetch(bearer: string, target?: string | null) { const res = await fetch(buildPath(target), { headers: { Accept: "application/json", Authorization: `Bearer ${bearer}` }, cache: "no-store", }); const text = await res.text().catch(() => ""); let json: any = null; try { json = text ? JSON.parse(text) : null; } catch {} return { res, json, text }; } export async function GET(req: NextRequest) { try { const userAt = req.cookies.get("ma_at")?.value; if (!userAt) return NextResponse.json({ error: "Not authenticated" }, { status: 401 }); const target = req.nextUrl.searchParams.get("target"); const r = await dFetch(userAt, target); if (!r.res.ok) { return NextResponse.json( { error: `Directus ${r.res.status}: ${r.text || r.res.statusText}` }, { status: r.res.status } ); } const rows: Array<{ id: number | string; name: string }> = r.json?.data ?? []; const data = rows.map(({ id, name }) => ({ id, name })); return NextResponse.json({ data }); } catch (e: any) { return NextResponse.json({ error: e?.message || "Failed to load lenses" }, { status: 500 }); } }