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

export const GET: RequestHandler = async ({ url, locals }) => {
  const accessToken = locals.session?.accessToken;
  if (!accessToken) {
    throw error(401, "Unauthorized");
  }

  const credentialId = url.searchParams.get("credentialId");
  const fieldId = url.searchParams.get("fieldId");
  if (!credentialId || !fieldId) {
    throw error(400, "Missing credentialId or fieldId");
  }

  try {
    const result = await optima.credential.fetchSecureValue(
      accessToken,
      credentialId,
      fieldId,
    );
    return json(result);
  } catch (err: unknown) {
    console.error("Failed to fetch secure value:", err);
    const status =
      err && typeof err === "object" && "status" in err
        ? (err as { status: number }).status
        : 500;
    throw error(status, "Failed to fetch secure value");
  }
};
