const db = require('../../db.js');
const storage_manager = require('./storage_manager.js');
const fs = require('fs');

let localCounter = 0;

async function checkAndRemoveInvalidEntries() {
   localCounter = 0;
   try {
      const measurementsRes = await db.query('SELECT id, path FROM measurements');
      for (const row of measurementsRes.rows) {
         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++;
         }
      }

      const allImages = await storage_manager.scanAllImages();
      for (const imagePath of allImages) {
         const entryRes = await db.query('SELECT id FROM measurements WHERE path = $1', [imagePath]);
         if (entryRes.rows.length === 0) {
            fs.unlinkSync(imagePath);
            console.log(`Deleted file at path: ${imagePath} as its database entry does not exist`);
            localCounter++;
         }
      }
      if (localCounter > 0) {
         console.log(`[INFO] ${localCounter} entrées ont été modifiées`);
         localCounter = 0; // Reset the counter after logging
      }
   } 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, 1000); // Every 10 seconds

// Initial run
checkAndRemoveInvalidEntries();