import { ENV } from '../config/env';

const BASE = `${ENV.DOLIBARR_URL}/api/index.php`;

const RATE_LIMIT_MS = 300;
let lastCallTime = 0;

const rateLimitedFetch = async (url: string, options: RequestInit = {}): Promise<Response> => {
  const now  = Date.now();
  const wait = RATE_LIMIT_MS - (now - lastCallTime);
  if (wait > 0) await new Promise((r) => setTimeout(r, wait));
  lastCallTime = Date.now();

  return fetch(url, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      'DOLAPIKEY':    ENV.DOLIBARR_KEY,
      'Accept':       'application/json',
      ...options.headers,
    },
    signal: AbortSignal.timeout(10_000),
  });
};

// Fonction interne unique utilisée par tous les services
export const dolibarrRequest = async <T>(
  endpoint: string,
  options:  RequestInit = {}
): Promise<T> => {
  const res  = await rateLimitedFetch(`${BASE}${endpoint}`, options);
  const text = await res.text();
  if (!res.ok) throw new Error(`Dolibarr ${res.status}: ${text}`);
  return JSON.parse(text) as T;
};

// API publique pour les services qui ont besoin de POST/PUT/DELETE
export const dolibarr = {
  get:    <T>(url: string)               => dolibarrRequest<T>(url),
  post:   <T>(url: string, body: unknown) => dolibarrRequest<T>(url, { method: 'POST',   body: JSON.stringify(body) }),
  put:    <T>(url: string, body: unknown) => dolibarrRequest<T>(url, { method: 'PUT',    body: JSON.stringify(body) }),
  delete: <T>(url: string)               => dolibarrRequest<T>(url, { method: 'DELETE' }),
};