export const runtime = "nodejs";

function getFoxitEsignAccessToken() {
  return process.env.FOXIT_ESIGN_API_ACCESS_TOKEN ?? "";
}

function pickEsignStatus(value: unknown): string | null {
  if (!value || typeof value !== "object") {
    return null;
  }

  const record = value as Record<string, unknown>;
  const folder = record.folder as Record<string, unknown> | undefined;
  const documentsList = Array.isArray(folder?.documentsList)
    ? (folder?.documentsList as Array<Record<string, unknown>>)
    : [];
  const firstDocument = documentsList[0];
  const directCandidates = [
    folder?.folderStatus,
    folder?.status,
    folder?.envelopeStatus,
    firstDocument?.contractStatus,
    record.folderStatus,
    record.status,
    record.signingStatus,
    record.overallStatus,
  ];

  for (const candidate of directCandidates) {
    if (typeof candidate === "string" && candidate.length > 0) {
      return candidate;
    }
  }

  const nestedCandidates = [record.data, record.result, record.response, record.payload, folder];
  for (const nested of nestedCandidates) {
    const nestedStatus = pickEsignStatus(nested);
    if (nestedStatus) {
      return nestedStatus;
    }
  }

  return null;
}

function pickFolderAccessURLForAuthor(value: unknown): string | null {
  if (!value || typeof value !== "object") {
    return null;
  }

  const record = value as Record<string, unknown>;
  const folder = record.folder as Record<string, unknown> | undefined;
  const directCandidates = [
    folder?.folderAccessURLForAuthor,
    folder?.folderAccessUrlForAuthor,
    record.folderAccessURLForAuthor,
    record.folderAccessUrlForAuthor,
  ];

  for (const candidate of directCandidates) {
    if (typeof candidate === "string" && candidate.length > 0) {
      return candidate;
    }
  }

  const nestedCandidates = [record.data, record.result, record.response, record.payload, folder];
  for (const nested of nestedCandidates) {
    const nestedUrl = pickFolderAccessURLForAuthor(nested);
    if (nestedUrl) {
      return nestedUrl;
    }
  }

  return null;
}

function normalizeEsignStatus(status: string | null): string | null {
  if (!status) {
    return null;
  }
  const normalized = status.trim().toUpperCase().replace(/_/g, " ");
  const knownStatuses = new Set([
    "EXECUTED",
    "SHARED",
    "DRAFT",
    "PARTIALLY SIGNED",
    "CANCELLED",
    "EXPIRED",
    "DELETED",
  ]);
  return knownStatuses.has(normalized) ? normalized : status.trim();
}

export async function GET(request: Request) {
  try {
    const url = new URL(request.url);
    const folderId = url.searchParams.get("folderId");

    if (!folderId) {
      return Response.json({ error: "Missing folderId query parameter." }, { status: 400 });
    }

    const accessToken = getFoxitEsignAccessToken();
    if (!accessToken) {
      return Response.json(
        { error: "FOXIT_ESIGN_API_ACCESS_TOKEN is not configured on the server." },
        { status: 500 }
      );
    }

    const foxitResponse = await fetch(
      `https://na1.foxitesign.foxit.com/api/folders/myfolder?folderId=${encodeURIComponent(folderId)}`,
      {
        method: "GET",
        headers: {
          Authorization: `Bearer ${accessToken}`,
        },
      }
    );

    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 eSign status response was not valid JSON.",
          status: foxitResponse.status,
          rawText,
        },
        { status: 502 }
      );
    }

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

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