makearmy-app/app/api/options/lens/route.ts

57 lines
2.1 KiB
TypeScript

// app/app/api/options/lens/route.ts
import { NextResponse } from "next/server";
import { directusFetch } from "@/lib/directus";
// Decide which collection to read based on target
function lensCollectionForTarget(target?: string) {
if (target === "settings_co2gan") return "laser_focus_lens"; // gantry
// fiber, uv, co2gal → scan lenses
return "laser_scan_lens";
}
export async function GET(req: Request) {
try {
const { searchParams } = new URL(req.url);
const target = searchParams.get("target") || undefined;
const q = (searchParams.get("q") || "").trim().toLowerCase();
const limit = Number(searchParams.get("limit") || "500");
const coll = lensCollectionForTarget(target);
// Request both possible PK fields, plus name & focal_length for labels
const url = `/items/${coll}?fields=submission_id,id,name,focal_length&limit=${limit}`;
const { data } = await directusFetch<{ data: any[] }>(url);
const list = Array.isArray(data) ? data : [];
const mapped = list.map((x) => {
const id = String(x.submission_id ?? x.id);
const label =
(x.name && String(x.name)) ||
(x.focal_length != null ? `F${x.focal_length} mm` : id);
const key =
(x.focal_length != null ? String(x.focal_length).padStart(6, "0") : "") +
" " +
label.toLowerCase();
return { id, label, key, focal: Number(x.focal_length ?? NaN) };
});
// Optional text filter
const filtered = q
? mapped.filter((m) => m.label.toLowerCase().includes(q))
: mapped;
// Prefer numeric focal_length ordering, fallback to label
filtered.sort((a, b) => {
const aNum = Number.isFinite(a.focal);
const bNum = Number.isFinite(b.focal);
if (aNum && bNum) return a.focal - b.focal;
if (aNum) return -1;
if (bNum) return 1;
return a.key.localeCompare(b.key);
});
return NextResponse.json({ data: filtered.map(({ id, label }) => ({ id, label })) });
} catch (e: any) {
return NextResponse.json({ error: e?.message || "Failed to load lens options" }, { status: 500 });
}
}