import { getRequestIP } from 'h3';
import logger from '~~/server/utils/logger';

export default defineNitroPlugin((nitroApp) => {
  nitroApp.hooks.hook('request', (event) => {
    // 1. On ignore les requêtes internes de Nuxt Image
    if (event.path.startsWith('/_ipx')) return;

    // 2. On ignore l’endpoint de log, qui est déjà tracé par logger client_log
    if (event.path === '/api/log') return;
    // message: 'logger_global',
    logger.info('logger_global', {
      label: 'back-end',
      internal: event._internal,
      method: event.method,
      url: event.path,
      ip: getRequestIP(event) || 'unknown',
    });
  });

  nitroApp.hooks.hook('error', (error, { event }) => {
    logger.error('Unhandled error', {
      message: error.message,
      stack: error.stack,
      internal: event._internal,
      method: event?.method,
      url: event?.path,
    });
  });
});