import { serverLanguageHeaders } from "@/lib/i18n/server";
import { normalizeDigitsDeep } from "@/lib/digits";
/**
 * Server-only API utilities for the homepage sections.
 * These functions use native `fetch()` with Next.js ISR revalidation.
 * They do NOT import Zustand or axios — safe to call in Server Components.
 */
import { cache } from "react";

import { API_BASE_URL } from "@/lib/api/config";

import type { BannerData, CommunityPost, HomeEvent, HomeOpportunity, SponsorItem } from "../types";

/**
 * Fetches banner images and statistics.
 * ISR: revalidates every 60 seconds.
 * React `cache()` deduplicates multiple calls in the same render.
 */
export const fetchBannerData = cache(async (): Promise<BannerData | null> => {
  try {
    const res = await fetch(`${API_BASE_URL}/banner-images/`, {
      next: { revalidate: 60 },
      headers: await serverLanguageHeaders(),
    });
    if (!res.ok) return null;
    const json = normalizeDigitsDeep(await res.json());
    return (json?.data as BannerData) ?? null;
  } catch {
    return null;
  }
});

/**
 * Fetches sponsor logos.
 * ISR: revalidates every 5 minutes.
 */
export const fetchSponsors = cache(async (): Promise<SponsorItem[]> => {
  try {
    const res = await fetch(`${API_BASE_URL}/sponsors/`, {
      next: { revalidate: 300 },
      headers: await serverLanguageHeaders(),
    });
    if (!res.ok) return [];
    const json = normalizeDigitsDeep(await res.json());
    return (json?.data as SponsorItem[]) ?? [];
  } catch {
    return [];
  }
});

/**
 * Fetches up to 6 volunteer opportunities for the homepage carousel.
 * ISR: revalidates every 2 minutes.
 */
export const fetchHomeVolunteerOpportunities = cache(
  async (): Promise<HomeOpportunity[]> => {
    try {
      const res = await fetch(
        `${API_BASE_URL}/list-volunteer-opportunities/?page=1&limit=6`,
        {
          next: { revalidate: 120 },
          headers: await serverLanguageHeaders(),
        }
      );
      if (!res.ok) return [];
      const json = normalizeDigitsDeep(await res.json());
      return (json?.data as HomeOpportunity[]) ?? [];
    } catch {
      return [];
    }
  }
);

/**
 * Fetches up to 6 learn-and-serve opportunities for the homepage carousel.
 * ISR: revalidates every 2 minutes.
 */
export const fetchHomeLearnServeOpportunities = cache(
  async (): Promise<HomeOpportunity[]> => {
    try {
      const res = await fetch(
        `${API_BASE_URL}/learn-serve-opportunities/?page=1&limit=6`,
        {
          next: { revalidate: 120 },
          headers: await serverLanguageHeaders(),
        }
      );
      if (!res.ok) return [];
      const json = normalizeDigitsDeep(await res.json());
      return (json?.data as HomeOpportunity[]) ?? [];
    } catch {
      return [];
    }
  }
);

/**
 * Fetches up to 6 events for the homepage.
 * ISR: revalidates every 2 minutes.
 */
export const fetchHomeEvents = cache(async (): Promise<HomeEvent[]> => {
  try {
    const res = await fetch(`${API_BASE_URL}/events/?page=1&limit=6`, {
      next: { revalidate: 120 },
      headers: await serverLanguageHeaders(),
    });
    if (!res.ok) return [];
    const json = normalizeDigitsDeep(await res.json());
    return (json?.data as HomeEvent[]) ?? [];
  } catch {
    return [];
  }
});

/**
 * Fetches community posts for homepage.
 * ISR: revalidates every 2 minutes.
 */
export const fetchHomeCommunityPosts = cache(
  async (): Promise<CommunityPost[]> => {
    try {
      const res = await fetch(`${API_BASE_URL}/posts/?page=1&limit=6`, {
        next: { revalidate: 120 },
        headers: await serverLanguageHeaders(),
      });
      if (!res.ok) return [];
      const json = normalizeDigitsDeep(await res.json());
      return (json?.data as CommunityPost[]) ?? [];
    } catch {
      return [];
    }
  }
);
