import { defineEventHandler, getQuery, readBody } from "h3";
// import { useStorage } from "@vueuse/core";
// import { buildState2, validationToken } from "../../utils/utils";
// import { validationToken } from "~/utils/globalMixin";

export default defineEventHandler(async (event) => {
  // defineAppConfig
  const baseUrl = process.env.VITE_BASE_URL;
  const method = event.node.req.method;
  const reqHeaders = getRequestHeaders(event);
  const config = useRuntimeConfig();
  // let token = useStorage("id_token", "GuestAccess").value;

  // return {
  //   reqHeaders,
  //   config,
  //   method,
  //   baseUrl,
  //   token,
  // };

  console.info("config", config);
  // console.info("reqHeaders", reqHeaders);

  try {
    if (method === "GET") {
      // Proxy GET requests to the external API
      const query = getQuery(event);
      const response = await $fetch(`${baseUrl}api/repo/schema`, {
        params: query,
      });
      return response;
    }

    if (method === "POST") {
      // Proxy POST requests to the external API
      const body = await readBody(event);
      const response = await $fetch(`${baseUrl}api/repo/schema`, {
        headers: {
          Authorization: reqHeaders.authorization,
        },
        method,
        body,
      });
      return response;
    }

    throw createError({ statusCode: 405, statusMessage: "Method Not Allowed" });
  } catch (error) {
    console.error("Error communicating with the external API:", error);
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.statusMessage || "Internal Server Error",
    });
  }
});
