-- =============================================================================
-- IDS - Pulizia Automatica Log Vecchi
-- =============================================================================
-- Mantiene solo gli ultimi 3 giorni di network_logs
-- Con 4.7M record/ora, 3 giorni = ~340M record massimi
-- Esegui giornalmente via cron: psql $DATABASE_URL < cleanup_old_logs.sql
-- =============================================================================

-- Conta log prima della pulizia
DO $$
DECLARE
  total_count bigint;
  old_count bigint;
BEGIN
  SELECT COUNT(*) INTO total_count FROM network_logs;
  SELECT COUNT(*) INTO old_count FROM network_logs WHERE timestamp < NOW() - INTERVAL '3 days';
  
  RAISE NOTICE 'Log totali: %', total_count;
  RAISE NOTICE 'Log da eliminare (>3 giorni): %', old_count;
END $$;

-- Elimina log più vecchi di 3 giorni
DELETE FROM network_logs 
WHERE timestamp < NOW() - INTERVAL '3 days';

-- Vacuum per liberare spazio fisico
VACUUM ANALYZE network_logs;

-- Conta log dopo pulizia
DO $$
DECLARE
  remaining_count bigint;
  db_size text;
BEGIN
  SELECT COUNT(*) INTO remaining_count FROM network_logs;
  SELECT pg_size_pretty(pg_database_size(current_database())) INTO db_size;
  
  RAISE NOTICE 'Log rimanenti: %', remaining_count;
  RAISE NOTICE 'Dimensione database: %', db_size;
END $$;
