import { getApiBaseUrl } from "@/components/main/BaseUrl";

export const SITE_URL =
  process.env.NEXT_PUBLIC_SITE_URL?.replace(/\/$/, "") ||
  "https://modstagram.com";

/** تعداد URL در هر فایل sitemap فرزند */
export const SITEMAP_PAGE_SIZE = 500;

/** سقف صفحات برای جلوگیری از انفجار ایندکس */
export const SITEMAP_MAX_PAGES = 80;

export const SITEMAP_REVALIDATE_SECONDS = 3600;

export type SitemapEntry = {
  url: string;
  lastModified?: Date | string;
  changeFrequency?:
    | "always"
    | "hourly"
    | "daily"
    | "weekly"
    | "monthly"
    | "yearly"
    | "never";
  priority?: number;
};

export function absoluteUrl(path: string): string {
  if (!path) return SITE_URL;
  if (path.startsWith("http://") || path.startsWith("https://")) return path;
  return `${SITE_URL}${path.startsWith("/") ? path : `/${path}`}`;
}

export async function sitemapFetchJson<T = unknown>(
  path: string,
  init?: RequestInit
): Promise<T | null> {
  const base = getApiBaseUrl().replace(/\/$/, "");
  const url = path.startsWith("http")
    ? path
    : `${base}${path.startsWith("/") ? path : `/${path}`}`;

  try {
    const res = await fetch(url, {
      ...init,
      next: { revalidate: SITEMAP_REVALIDATE_SECONDS },
      headers: {
        Accept: "application/json",
        ...(init?.headers || {}),
      },
    });
    if (!res.ok) {
      console.error(`[sitemap] ${res.status} ${url}`);
      return null;
    }
    return (await res.json()) as T;
  } catch (err) {
    console.error(`[sitemap] fetch failed ${url}`, err);
    return null;
  }
}

export function clampPages(totalPages: number): number {
  if (!Number.isFinite(totalPages) || totalPages < 1) return 1;
  return Math.min(Math.max(1, Math.floor(totalPages)), SITEMAP_MAX_PAGES);
}

export function pagesFromTotal(totalItems: number, pageSize = SITEMAP_PAGE_SIZE) {
  if (!totalItems || totalItems < 1) return 1;
  return clampPages(Math.ceil(totalItems / pageSize));
}
