import type { APIRoute } from "astro";
import * as TOML from "@iarna/toml";
import { config } from "../../config";

export const GET: APIRoute = async ({ request }) => {
  try {
    // Check if resume TOML content is configured
    if (!config.resumeConfig.tomlFile || !config.resumeConfig.tomlFile.trim()) {
      return new Response("Resume not configured", { status: 404 });
    }

    let tomlContent: string;

    if (config.resumeConfig.tomlFile.startsWith("/")) {
      const url = new URL(request.url);
      const baseUrl = `${url.protocol}//${url.host}`;

      const response = await fetch(`${baseUrl}${config.resumeConfig.tomlFile}`);

      if (!response.ok) {
        throw new Error(
          `Failed to fetch resume TOML: ${response.status} ${response.statusText}`,
        );
      }

      tomlContent = await response.text();
    } else {
      tomlContent = config.resumeConfig.tomlFile;
    }
    const resumeData = TOML.parse(tomlContent);

    return new Response(JSON.stringify(resumeData), {
      headers: {
        "Content-Type": "application/json",
        "Cache-Control": "public, max-age=300",
      },
    });
  } catch (error) {
    console.error("Error parsing resume TOML:", error);
    return new Response("Error parsing resume data", { status: 500 });
  }
};
