import { headers } from 'next/headers';
import {
	DEFAULT_CATEGORIES,
	DEFAULT_FEATURED_CATEGORIES,
	DEFAULT_PRODUCTS,
	type CategoryTreeNode,
	type FeaturedCategory,
	type Product
} from '@/components/store/config/defaultStoreConfig';
import { resolveStoreIdentifier } from '@/lib/storeHost';

export type StoreCatalog = {
	products: Product[];
	categories: string[];
	categoryTree: CategoryTreeNode[];
	featuredCategories: FeaturedCategory[];
};

const FALLBACK: StoreCatalog = {
	products: DEFAULT_PRODUCTS,
	categories: DEFAULT_CATEGORIES,
	categoryTree: [],
	featuredCategories: DEFAULT_FEATURED_CATEGORIES
};


/**
 * Carga el catálogo real del ERP (productos, categorías y destacadas) resuelto
 * por subdominio. Si el backend falla, cae al catálogo de ejemplo para no romper
 * el render. Un tenant válido pero vacío devuelve catálogo vacío (no fallback).
 */
export async function loadStoreCatalog(): Promise<StoreCatalog> {
	const backendUrl = process.env.BACKEND_URL;
	const appToken = process.env.STORE_APP_TOKEN;

	const hdrs = await headers();
	const host = hdrs.get('host') ?? '';
	const subdominio = resolveStoreIdentifier(host) ?? process.env.STORE_SUBDOMINIO_DEV;

	if (!backendUrl || !appToken || !subdominio) {
		return FALLBACK;
	}

	const url = `${backendUrl}/api/v1/store/bootstrap?subdominio=${encodeURIComponent(subdominio)}&limit=5000`;
	// Next no guarda en su caché de fetch respuestas de más de 2 MB (~4.500 productos):
	// por encima de eso el catálogo se pide en cada render. Ahí conviene paginar en el servidor.

	try {
		const res = await fetch(url, {
			headers: { 'x-app-key': appToken },
			// `revalidate: 60` es el techo de seguridad; `tags` permite invalidar
			// al instante desde /api/revalidate cuando el panel admin publica.
			next: { revalidate: 60, tags: [`store-catalog-${subdominio}`] },
			signal: AbortSignal.timeout(8000)
		});
		if (!res.ok) return FALLBACK;
		const data = (await res.json()) as Partial<StoreCatalog>;
		return {
			products: data.products ?? [],
			categories: data.categories?.length ? data.categories : ['Todos'],
			categoryTree: data.categoryTree ?? [],
			featuredCategories: data.featuredCategories ?? []
		};
	} catch {
		return FALLBACK;
	}
}
