import { optima } from "$lib";
import { json, error } from "@sveltejs/kit";
import type { RequestHandler } from "./$types";

/** GET /procurement/catalog/inventory?id=<identifier> */
export const GET: RequestHandler = async ({ url, locals }) => {
    const accessToken = locals.session?.accessToken;
    if (!accessToken) throw error(401, "Unauthorized");

    const identifier = url.searchParams.get("id");
    if (!identifier) throw error(400, "Missing id parameter");

    try {
        const result = await optima.procurement.fetchInventory(accessToken, identifier);
        return json(result);
    } catch (err: unknown) {
        console.error("Failed to fetch product inventory:", err);
        const status =
            err && typeof err === "object" && "status" in err
                ? (err as { status: number }).status
                : 500;
        throw error(status, "Failed to fetch product inventory");
    }
};
