/**
 * Full-stack audit (8 Nov 2026, backend 409e2f4) — discovery domain fixes S-DIS-n.
 */
import { test, describe } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { collectFaqPages, FAQ_PAGE_LIMIT } from "@/features/info/faqPages";
import { toHeroBanners } from "@/features/home/homeHeroBanners";
import type { ApiResponse, FaqItem } from "@/lib/api/types";

const faq = (id: number): FaqItem =>
  ({ id, question_en: `Q${id}`, question_ar: `س${id}`, answer_en: "a", answer_ar: "ج" }) as FaqItem;

const page = (ids: number[], totalPages?: number): ApiResponse<FaqItem[]> => ({
  key: "success",
  msg: "",
  code: 200,
  response_status: { error: false, validation_errors: {} },
  data: ids.map(faq),
  ...(totalPages ? { meta: { pagination: { page: 1, limit: FAQ_PAGE_LIMIT, total: ids.length, total_pages: totalPages } } } : {}),
});

describe("S-DIS-1: the FAQ page shows every question, not only the first 100 (PDF p.32)", () => {
  test("asks for the server's real cap and walks every page", async () => {
    const calls: Array<[number, number]> = [];
    const result = await collectFaqPages(async (p, limit) => {
      calls.push([p, limit]);
      return page(p === 1 ? [1, 2] : p === 2 ? [3] : [4], 3);
    });
    assert.deepEqual(calls, [[1, 100], [2, 100], [3, 100]]);
    assert.deepEqual(result.data.map((f) => f.id), [1, 2, 3, 4]);
    assert.equal(result.key, "success");
  });

  test("a response without pagination meta is a single page", async () => {
    let count = 0;
    const result = await collectFaqPages(async () => {
      count += 1;
      return page([7]);
    });
    assert.equal(count, 1);
    assert.deepEqual(result.data.map((f) => f.id), [7]);
  });

  test("a failed later page rejects instead of showing a silently truncated list", async () => {
    await assert.rejects(
      collectFaqPages(async (p) => {
        if (p === 2) throw new Error("boom");
        return page([1], 2);
      })
    );
  });

  test("neither FAQ entry point sends the capped limit=1000 any more", () => {
    for (const file of ["src/app/(main)/faq/page.tsx", "src/features/info/components/Faq.tsx"]) {
      const source = readFileSync(file, "utf8");
      assert.ok(!source.includes("limit=1000") && !source.includes("limit: 1000"), file);
      assert.ok(source.includes("collectFaqPages"), file);
    }
  });
});

describe("BE-290 resolved at 409e2f4: /banner-images/ (reversed) and /home/ hero.banners agree", () => {
  test("insertion-ordered /banner-images/ rows come out in the /home/ latest() order", () => {
    // Staging, 8 Nov: /home/ hero ids 6,5,3,2,1; /banner-images/ rows 1,2,3,5,6.
    const rows = [1, 2, 3, 5, 6].map((id) => ({ image: `https://x/${id}.png`, banner_url: null }));
    assert.deepEqual(
      toHeroBanners(rows).map((b) => b.image),
      [6, 5, 3, 2, 1].map((id) => `https://x/${id}.png`)
    );
  });
});
