import { NextResponse } from "next/server";

export const runtime = "nodejs"; // Force Node runtime

const GHOST_API_URL = process.env.GHOST_API_URL;
const GHOST_API_KEY = process.env.GHOST_API_KEY;

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

  if (!slug) {
    return NextResponse.json({ error: "Slug is required" }, { status: 400 });
  }

  try {
    // Debug: show whether fetch is present/mocked

    /* eslint-disable @typescript-eslint/no-explicit-any */
    console.log(
      "DEBUG fetch in fetchProject:",
      typeof (globalThis as any).fetch,
      "globalIsMock:",
      !!(globalThis as any).fetch?._isMockFunction,
    );

    // Try global fetch first (as tests often mock it). If it fails or returns undefined,
    // fall back to dynamically importing node-fetch.
    let response: any;

    if (typeof (globalThis as any).fetch === "function") {
      try {
        response = await (globalThis as any).fetch(
          `${GHOST_API_URL}/ghost/api/content/posts/slug/${slug}/?key=${GHOST_API_KEY}`,
        );
      } catch (_e) {
        response = undefined;
      }
    }

    if (!response || typeof response.ok === "undefined") {
      try {
        const mod = await import("node-fetch");
        const nodeFetch = (mod as any).default ?? mod;
        response = await (nodeFetch as any)(
          `${GHOST_API_URL}/ghost/api/content/posts/slug/${slug}/?key=${GHOST_API_KEY}`,
        );
      } catch (_err) {
        response = undefined;
      }
    }
    /* eslint-enable @typescript-eslint/no-explicit-any */

    // Debug: inspect the response returned from the fetch

    // Debug: inspect the response returned from the fetch

    console.log("DEBUG fetch response:", response);

    if (!response || !response.ok) {
      throw new Error(
        `Failed to fetch post: ${response?.statusText ?? "no response"}`,
      );
    }

    const post = await response.json();
    return NextResponse.json(post);
  } catch (error) {
    console.error("Failed to fetch post from Ghost:", error);
    return NextResponse.json(
      { error: "Failed to fetch project" },
      { status: 500 },
    );
  }
}
