import { state } from './state.js';

const cache = new Map();

export async function api(endpoint, options = {}) {
  const url = endpoint.startsWith('http') ? endpoint : endpoint;
  const headers = { 'Content-Type': 'application/json' };
  const token = state.getToken();
  if (token) headers['Authorization'] = `Bearer ${token}`;

  const config = { headers, ...options };
  if (config.body && typeof config.body === 'object') {
    config.body = JSON.stringify(config.body);
  }

  try {
    const res = await fetch(url, config);
    if (res.status === 401) {
      state.logout();
      return null;
    }
    const text = await res.text();
    try {
      return JSON.parse(text);
    } catch {
      console.error('API parse error:', endpoint, text.slice(0, 200));
      return null;
    }
  } catch (err) {
    console.error('API fetch error:', endpoint, err);
    return null;
  }
}

export async function cachedApi(endpoint, ttlMs = 60000) {
  const key = endpoint;
  const cached = cache.get(key);
  if (cached && Date.now() - cached.time < ttlMs) return cached.data;
  const data = await api(endpoint);
  if (data) cache.set(key, { data, time: Date.now() });
  return data;
}

export function clearCache(pattern) {
  if (!pattern) { cache.clear(); return; }
  for (const key of cache.keys()) {
    if (key.includes(pattern)) cache.delete(key);
  }
}
