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

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

    const url = new URL(request.url);
    const baseUrl = `${url.protocol}//${url.host}`;

    // Fetch the TOML file from the public directory
    const response = await fetch(`${baseUrl}${siteConfig.resume.tomlFile}`);

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

    const tomlContent = await response.text();
    const resumeData = TOML.parse(tomlContent);

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