import "@testing-library/jest-dom";
import { GET } from "@/app/sitemap.xml/route";

jest.mock("next/server", () => ({
  NextResponse: jest.fn().mockImplementation((body: unknown, init?: ResponseInit) => {
    const response = {
      body,
      init,
    };
    return response;
  }),
}));

// Sitemap XML used by node-fetch mock
const sitemapXml = `
  <urlset xmlns="https://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
      <loc>https://dki.one/</loc>
    </url>
    <url>
      <loc>https://dki.one/legal-notice</loc>
    </url>
    <url>
      <loc>https://dki.one/privacy-policy</loc>
    </url>
    <url>
      <loc>https://dki.one/projects/just-doing-some-testing</loc>
    </url>
    <url>
      <loc>https://dki.one/projects/blockchain-based-voting-system</loc>
    </url>
  </urlset>
`;

// Mock node-fetch for sitemap endpoint (hoisted by Jest)
jest.mock("node-fetch", () => ({
  __esModule: true,
  default: jest.fn((_url: string) =>
    Promise.resolve({ ok: true, text: () => Promise.resolve(sitemapXml) }),
  ),
}));

describe("Sitemap Component", () => {
  beforeAll(() => {
    process.env.NEXT_PUBLIC_BASE_URL = "https://dki.one";

    // Provide sitemap XML directly so route uses it without fetching
    process.env.GHOST_MOCK_SITEMAP = sitemapXml;

    // Mock global.fetch too, to avoid any network calls
    global.fetch = jest.fn().mockImplementation((url: string) => {
      if (url.includes("/api/sitemap")) {
        return Promise.resolve({
          ok: true,
          text: () => Promise.resolve(sitemapXml),
        });
      }
      return Promise.reject(new Error(`Unknown URL: ${url}`));
    });
  });

  it("should render the sitemap XML", async () => {
    const response = await GET();

    expect(response.body).toContain(
      '<urlset xmlns="https://www.sitemaps.org/schemas/sitemap/0.9">',
    );
    expect(response.body).toContain("<loc>https://dki.one/</loc>");
    expect(response.body).toContain("<loc>https://dki.one/legal-notice</loc>");
    expect(response.body).toContain(
      "<loc>https://dki.one/privacy-policy</loc>",
    );
    expect(response.body).toContain(
      "<loc>https://dki.one/projects/just-doing-some-testing</loc>",
    );
    expect(response.body).toContain(
      "<loc>https://dki.one/projects/blockchain-based-voting-system</loc>",
    );
    // Note: Headers are not available in test environment
  });
});
