// app/api/options/_lib.ts import { NextRequest, NextResponse } from "next/server"; export type Option = { id: string | number; label: string }; export function readCookie(name: string, cookieHeader: string) { const m = cookieHeader.match(new RegExp(`(?:^|;\\s*)${name}=([^;]+)`)); return m?.[1] ?? null; } export function getAuthHeaders(req: NextRequest) { const cookieHeader = req.headers.get("cookie") ?? ""; const ma_at = readCookie("ma_at", cookieHeader); const headers: Record = { Accept: "application/json" }; if (cookieHeader) headers.cookie = cookieHeader; if (ma_at) headers.authorization = `Bearer ${ma_at}`; return headers; } export function apiBase() { const base = (process.env.DIRECTUS_URL || process.env.NEXT_PUBLIC_API_BASE_URL || "").replace(/\/$/, ""); if (!base) throw new Error("Missing DIRECTUS_URL or NEXT_PUBLIC_API_BASE_URL"); return base; } export async function dFetchJSON(req: NextRequest, path: string): Promise { const res = await fetch(`${apiBase()}${path}`, { headers: getAuthHeaders(req), cache: "no-store", }); if (!res.ok) { const text = await res.text().catch(() => ""); throw new Error(`Directus ${res.status} fetching ${path}: ${text}`); } return res.json() as Promise; } export function applyQFilter(rows: T[], q: string | null, pick: (row: T) => string): T[] { if (!q) return rows; const needle = q.trim().toLowerCase(); if (!needle) return rows; return rows.filter((r) => (pick(r) || "").toLowerCase().includes(needle)); } export function json(data: Option[] | { data: Option[] }, status = 200) { const body = Array.isArray(data) ? { data } : data; return NextResponse.json(body, { status, headers: { "cache-control": "no-store" } }); }