type CacheEntry = {
  body: string;
  status: number;
  expiresAt: number;
};

const PREFIX = "adminCache:";

export interface CachedFetchOptions {
  ttl?: number;
}

export async function cachedFetch(
  url: string,
  options: CachedFetchOptions = {}
): Promise<Response> {
  const ttl = options.ttl ?? 60;
  const key = PREFIX + url;
  const now = Date.now();

  try {
    const raw = sessionStorage.getItem(key);
    if (raw) {
      const entry = JSON.parse(raw) as CacheEntry;
      if (
        entry &&
        typeof entry.expiresAt === "number" &&
        entry.expiresAt > now
      ) {
        return new Response(entry.body, {
          status: entry.status,
          headers: { "Content-Type": "application/json" },
        });
      }
    }
  } catch {
    // sessionStorage no disponible o entrada inválida
  }

  const res = await fetch(url);

  if (res.ok) {
    try {
      const body = await res.text();
      sessionStorage.setItem(
        key,
        JSON.stringify({
          body,
          status: res.status,
          expiresAt: now + ttl * 1000,
        })
      );
      return new Response(body, {
        status: res.status,
        headers: { "Content-Type": "application/json" },
      });
    } catch {
      // no se pudo cachear, devolver la respuesta original
    }
  }

  return res;
}
