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

/** GET /procurement/catalog/linked?id=<identifier> — fetch linked items */
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 item id");

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

/** POST /procurement/catalog/linked — link or unlink items */
export const POST: RequestHandler = async ({ request, locals }) => {
  const accessToken = locals.session?.accessToken;
  if (!accessToken) throw error(401, "Unauthorized");

  const body = await request.json();
  const { action, identifier, targetId } = body;

  if (!identifier || !targetId || !action) {
    throw error(400, "Missing identifier, targetId, or action");
  }

  try {
    if (action === "link") {
      const result = await optima.procurement.linkItem(
        accessToken,
        identifier,
        targetId,
      );
      return json(result);
    } else if (action === "unlink") {
      const result = await optima.procurement.unlinkItem(
        accessToken,
        identifier,
        targetId,
      );
      return json(result);
    } else {
      throw error(400, "Invalid action — must be 'link' or 'unlink'");
    }
  } catch (err: unknown) {
    console.error(`Failed to ${action} items:`, err);
    const status =
      err && typeof err === "object" && "status" in err
        ? (err as { status: number }).status
        : 500;
    throw error(status, `Failed to ${action} items`);
  }
};
