// app/lasers/[id]/page.tsx
import { cookies } from "next/headers";
import { redirect, notFound } from "next/navigation";
import { dxGET } from "@/lib/directus";
import LaserDetailsClient from "./LaserDetailsClient";

const FIELD_GROUPS = [
    {
        title: "General Information",
        fields: {
            make: "Make",
            model: "Model",
            op: "Pulse Operation Mode",
            notes: "Notes",
        },
    },
{
    title: "Optical Specifications",
    fields: {
        w: "Laser Wattage (W)",
        mj: "milliJoule Max (mJ)",
        nm: "Wavelength (nm)",
        kHz: "Pulse Repetition Rate (kHz)", // NOTE: schema uses kHz (not k_hz)
        ns: "Pulse Width (ns)",
        d: "Beam Diameter (mm)",
        m2: "M² - Quality",
        instability: "Instability",
        polarization: "Polarization",
        band: "Band (nm)",
        anti: "Anti-Reflection Coating",
        mw: "Red Dot Wattage (mW)",
    },
},
{
    title: "Electrical & Timing",
    fields: {
        v: "Operating Voltage (V)",
        temp_op: "Operating Temperature (°C)",
        temp_store: "Storage Temperature (°C)",
        l_on: "l_on",
        l_off: "l_off",
        mj_c: "mj_c",
        ns_c: "ns_c",
        d_c: "d_c",
        on_c: "on_c",
        off_c: "off_c",
    },
},
{
    title: "Integration & Physical",
    fields: {
        cable: "Cable Length (m)",
        cooling: "Cooling Method",
        weight: "Weight (kg)",
        dimensions: "Dimensions (cm)",
    },
},
] as const;

export default async function Page(
    { params }: { params: Promise<{ id: string }> } // Next 15: params is Promise
) {
    const { id: submissionId } = await params;

    const jar = await cookies(); // Next 15: cookies() is async
    const token = jar.get("ma_at")?.value;
    if (!token) {
        redirect(`/auth/sign-in?next=${encodeURIComponent(`/lasers/${submissionId}`)}`);
    }

    const bearer = `Bearer ${token}`;

    // Pull EVERYTHING the role can see. (No fragile field list.)
    const res = await dxGET<any>(
        `/items/laser_source/${encodeURIComponent(submissionId)}?fields=*`,
                                 bearer
    );
    const laser = res?.data ?? res ?? null;
    if (!laser) notFound();

    return <LaserDetailsClient laser={laser} fieldGroups={FIELD_GROUPS as any} />;
}
