// Réception des événements Dolibarr (module Webhook actif dans Dolibarr)
import type { Request, Response } from 'express';
import { cache } from '../services/cache.service';

interface DolibarrWebhookEvent {
  action: string;      // ex: PRODUCT_MODIFY, PRODUCT_SET_MULTILANGS
  object: string;       // ex: "product"
  triggercode?: string;
  data?: { id?: number; ref?: string };
}

export function handleDolibarrWebhook(req: Request, res: Response) {
  const event = req.body as DolibarrWebhookEvent;
  console.log('[Webhook Dolibarr]', event.action, event.object);

  // Exemples d'actions à brancher :
  // if (event.action === 'ORDER_VALIDATE') { ... }
  // if (event.action === 'INVOICE_SENT')   { ... }

  const productActions = [
    'PRODUCT_CREATE',
    'PRODUCT_MODIFY',
    'PRODUCT_DELETE',
    'PRODUCT_SET_MULTILANGS',
  ];

  const categoryActions = [
    'CATEGORY_LINK', // rattachement produit ↔ catégorie
    'CATEGORY_UNLINK',
    'CATEGORY_MODIFY',
  ];

  if (productActions.includes(event.action)) {
    // Invalide le cache produit spécifique + la liste globale
    if (event.data?.id) cache.delete(`products:${event.data.id}`);
    cache.delete('products:all');
    invalidateAllCategoryProductCaches();
    console.log('[Cache] Invalidé après modification produit');
  }

  if (categoryActions.includes(event.action)) {
    // Un produit a changé de catégorie → tout le cache catégories est obsolète
    cache.delete('categories:tree');
    invalidateAllCategoryProductCaches();
    console.log('[Cache] Invalidé après changement de catégorie');
  }

  res.status(200).json({ received: true });
}

// Purge toutes les clés categories:{id}:products sans connaître les IDs à l'avance
function invalidateAllCategoryProductCaches() {
  cache.keys()
    .filter((key) => key.startsWith('categories:') && key.endsWith(':products'))
    .forEach((key) => cache.delete(key));
}