// app/api/options/lens/route.ts export const dynamic = "force-dynamic"; import { NextRequest, NextResponse } from "next/server"; const BASE = ( process.env.DIRECTUS_URL || process.env.NEXT_PUBLIC_API_BASE_URL || "" ).replace(/\/$/, ""); function buildPath(target?: string | null) { // CO2 Gantry → focus lenses (name) // everything else (Fiber/UV/CO2 Galvo) → scan lenses (field_size + focal_length) const isGantry = target === "co2-gantry"; if (isGantry) { const url = new URL(`${BASE}/items/laser_focus_lens`); url.searchParams.set("fields", "id,name"); url.searchParams.set("sort", "name"); return String(url); } const url = new URL(`${BASE}/items/laser_scan_lens`); url.searchParams.set("fields", "id,field_size,focal_length"); url.searchParams.set("sort", "field_size,focal_length"); 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: any[] = r.json?.data ?? []; const isGantry = target === "co2-gantry"; const data = rows.map((row) => { if (isGantry) { // Focus lens: label is just the stored name return { id: row.id, name: row.name, label: row.name }; } // Scan lens: label "300x300 mm | F420" etc const fs = row.field_size != null && row.field_size !== "" ? `${row.field_size} mm` : ""; const fl = row.focal_length != null && row.focal_length !== "" ? `F${row.focal_length}` : ""; const label = [fs, fl].filter(Boolean).join(" | "); return { id: row.id, name: label, label }; }); return NextResponse.json({ data }); } catch (e: any) { return NextResponse.json( { error: e?.message || "Failed to load lenses" }, { status: 500 } ); } }