import { localizedMetadata } from "@/lib/i18n/serverMetadata";
import { serverLanguageHeaders } from "@/lib/i18n/server";
import { normalizeDigitsDeep } from "@/lib/digits";
import type { Metadata } from "next";
import Faq from "@/features/info/components/Faq";
import { API_BASE_URL } from "@/lib/api/config";
import type { ApiResponse, FaqItem } from "@/lib/api/types";
import { collectFaqPages } from "@/features/info/faqPages";

/** Every page: the API caps one page at 100 questions (see `collectFaqPages`). */
const fetchFaqs = (headers: Record<string, string>): Promise<ApiResponse<FaqItem[]>> =>
  collectFaqPages((page, limit) => fetchFaqPage(page, limit, headers));

async function fetchFaqPage(page: number, limit: number, headers: Record<string, string>): Promise<ApiResponse<FaqItem[]>> {
  const res = await fetch(`${API_BASE_URL}/faqs/?page=${page}&limit=${limit}`, {
    next: { revalidate: 3600 }, // Cache for 1 hour
    headers,
  });
  if (!res.ok) {
    throw new Error("Failed to fetch FAQs");
  }

  const response = (normalizeDigitsDeep(await res.json())) as ApiResponse<FaqItem[]>;
  if (response.key !== "success" || response.response_status.error) {
    throw new Error(response.msg || "Failed to fetch FAQs");
  }

  return response;
}

const pageMetadata: Metadata = {
  title: "Frequently asked questions",
  description:
    "Answers about volunteering, publishing opportunities and using Fursa.",
};

export async function generateMetadata(): Promise<Metadata> {
  return localizedMetadata(pageMetadata);
}

export default async function Page() {
  // Read the language cookie *outside* the try block: `cookies()` opts the route into dynamic
  // rendering by throwing during a static pass, and the catch below must not swallow that.
  const headers = await serverLanguageHeaders();
  let initialFaqs: FaqItem[] = [];
  try {
    const response = await fetchFaqs(headers);
    initialFaqs = response.data ?? [];
  } catch (err) {
    console.error("Error fetching FAQs on server:", err);
  }

  return <Faq initialFaqs={initialFaqs} />;
}
