import db from '../../db.js';
import path from 'path';
import storageManager from '../data/storageManager.js';
import fs from 'fs';

let localCounter = 0;

async function checkAndRemoveInvalidEntries() {
   localCounter = 0;
   console.log('[INFO] Vérification et suppression des entrées invalides...');
   try {
      const measurementsRes = await db.query('SELECT id, path FROM measurements');
      //console.log('Fetched measurements:', measurementsRes.rows);
      for (const row of measurementsRes.rows) {
         //console.log('Checking file path:', row.path);
         if (!fs.existsSync(row.path)) {
            await db.query('DELETE FROM measurements WHERE id = $1', [row.id]);
            console.log(`Deleted invalid measurement entry with id: ${row.id}`);
            localCounter++;
         }
      }

      // Scan all images in storage
      const allImages = await storageManager.scanAllImages();
      //console.log('Scanned all images:', allImages);
      for (const imagePath of allImages) {
         const entryRes = await db.query('SELECT id FROM measurements WHERE path = $1', [imagePath]);
         if (entryRes.rows.length === 0) {
            // Remove the file if the entry does not exist
            fs.unlinkSync(imagePath);
            console.log(`Deleted file at path: ${imagePath} as its database entry does not exist`);
            localCounter++; // Increment counter if entry is deleted
         }
      }
      if (localCounter > 0) {
         console.log(`[INFO] ${localCounter} entrées ont été modifiées`);
      } else {
         console.log('[INFO] Aucune entrée n\'a été modifiée.');
      }
   } catch (err) {
      console.error('Error checking and removing invalid entries:', err);
   }
}



// Run the check periodically
console.log('[INFO] Activation du FileWatcher pour surveiller les fichiers invalides...')
setInterval(checkAndRemoveInvalidEntries, 10000); // Every 10 seconds

// Initial run
checkAndRemoveInvalidEntries();