import { readFile } from "node:fs/promises";
import path from "node:path";

export const runtime = "nodejs";

type GenerateReportRequest = {
  documentValues: Record<string, unknown>;
};

function getFoxitCredentials() {
  const clientId = process.env.FOXIT_DOCGEN_CLIENT_ID ?? process.env.FOXIT_CLIENT_ID;
  const clientSecret = process.env.FOXIT_DOCGEN_CLIENT_SECRET ?? process.env.FOXIT_CLIENT_SECRET;

  return { clientId, clientSecret };
}

export async function POST(request: Request) {
  try {
    const body = (await request.json()) as GenerateReportRequest;
    if (!body?.documentValues || typeof body.documentValues !== "object") {
      return Response.json({ error: "Missing documentValues in request body." }, { status: 400 });
    }

    const templatePath = path.join(
      process.cwd(),
      "inputs",
      "templates",
      "Candidate_Pipeline_Report_Template.docx"
    );
    const templateBuffer = await readFile(templatePath);
    const base64FileString = templateBuffer.toString("base64");

    const foxitPayload = {
      outputFormat: "pdf",
      documentValues: body.documentValues,
      base64FileString,
    };

    const headers: Record<string, string> = {
      "Content-Type": "application/json",
    };

    const { clientId, clientSecret } = getFoxitCredentials();
    if (clientId) {
      headers.client_id = clientId;
    }
    if (clientSecret) {
      headers.client_secret = clientSecret;
    }

    const foxitResponse = await fetch(
      "https://na1.fusion.foxit.com/document-generation/api/GenerateDocumentBase64",
      {
        method: "POST",
        headers,
        body: JSON.stringify(foxitPayload),
      }
    );

    const rawText = await foxitResponse.text();
    let foxitJson: Record<string, unknown> = {};
    try {
      foxitJson = rawText ? (JSON.parse(rawText) as Record<string, unknown>) : {};
    } catch {
      return Response.json(
        {
          error: "Foxit response was not valid JSON.",
          status: foxitResponse.status,
          rawText,
        },
        { status: 502 }
      );
    }

    if (!foxitResponse.ok) {
      return Response.json(
        {
          error: "Foxit API call failed.",
          status: foxitResponse.status,
          details: foxitJson,
        },
        { status: 502 }
      );
    }

    return Response.json({ foxitResponse: foxitJson });
  } catch (error) {
    const message = error instanceof Error ? error.message : "Unknown server error";
    return Response.json({ error: message }, { status: 500 });
  }
}
