import type { APIRoute } from "astro";
import { config } from "../../../config";
import type { ResumeData } from "../../../types";
import * as TOML from "@iarna/toml";
import { renderToStream } from "@react-pdf/renderer";
import { ResumeDocument } from "../../../pdf/ResumeDocument";
import { pdfIconPaths } from "../../../config/icons";

const generatePDF = async (data: ResumeData) => {
  const resumeConfig = config.resumeConfig;

  const icons: { [key: string]: string } = {
    email: pdfIconPaths.email,
    phone: pdfIconPaths.phone,
  };

  if (data.basics.profiles) {
    for (const profile of data.basics.profiles) {
      const key = profile.network.toLowerCase();
      if (pdfIconPaths[key]) {
        icons[key] = pdfIconPaths[key];
      }
    }
  }

  return await renderToStream(ResumeDocument({ data, resumeConfig, icons }));
};

export const GET: APIRoute = async ({ request }) => {
  try {
    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: ${response.status} ${response.statusText}`,
        );
      }

      tomlContent = await response.text();
    } else {
      tomlContent = config.resumeConfig.tomlFile;
    }

    const resumeData: ResumeData = TOML.parse(
      tomlContent,
    ) as unknown as ResumeData;

    const stream = await generatePDF(resumeData);

    return new Response(stream as any, {
      headers: {
        "Content-Type": "application/pdf",
        "Content-Disposition": `attachment; filename="Atridad_Lahiji_Resume.pdf"`,
      },
    });
  } catch (error) {
    console.error("Error generating PDF:", error);
    return new Response("Error generating PDF", { status: 500 });
  }
};

export const POST: APIRoute = async ({ request }) => {
  try {
    const { toml: tomlContent } = await request.json();

    if (!tomlContent.trim()) {
      return new Response("TOML content is required", { status: 400 });
    }

    let resumeData: ResumeData;
    try {
      resumeData = TOML.parse(tomlContent) as unknown as ResumeData;
    } catch (parseError) {
      return new Response(
        `Invalid TOML format: ${parseError instanceof Error ? parseError.message : "Unknown error"}`,
        { status: 400 },
      );
    }

    if (!resumeData.basics?.name) {
      return new Response("Resume must include basics.name", { status: 400 });
    }

    const stream = await generatePDF(resumeData);
    const filename = `${resumeData.basics.name.replace(/[^a-zA-Z0-9]/g, "_")}_Resume.pdf`;

    return new Response(stream as any, {
      headers: {
        "Content-Type": "application/pdf",
        "Content-Disposition": `attachment; filename="${filename}"`,
      },
    });
  } catch (error) {
    console.error("Error generating PDF:", error);
    return new Response("Error generating PDF", { status: 500 });
  }
};
