import { dolibarrRequest } from './dolibarr.service';
import { cache }           from './cache.service';
import type { DolibarrProduct, Product } from '../models/product.model';
import { toProduct }       from '../models/product.model';

export const ProductService = {
  // Retourne les données brutes Dolibarr (utilisé par prefetch)
  getAllRaw: async (): Promise<DolibarrProduct[]> => {
    const data = dolibarrRequest<DolibarrProduct[]>(
      '/products?sortfield=t.ref&sortorder=ASC&limit=100'
    );

    return data;
  },

  // Retourne les produits transformés (avec cache)
  getAll: async (options?: { inStock?: boolean }): Promise<Product[]> => {
    const cacheKey = options?.inStock ? 'products:inStock' : 'products:all';
    const cached = cache.get<Product[]>(cacheKey);
    if (cached) return cached;

    const raw  = await ProductService.getAllRaw();
    let data = raw.map(toProduct);

    if (options?.inStock) {
      data = data.filter((p) => p.inStock);
    }

    cache.set(cacheKey, data, 600);
    return data;
  },

  getById: async (id: number): Promise<DolibarrProduct> => {
    const cached = cache.get<DolibarrProduct>(`products:${id}`);
    if (cached) return cached;

    const data = await dolibarrRequest<DolibarrProduct>(`/products/${id}`);
    cache.set(`products:${id}`, data, 600);
    return data;
  },
};
