import fs from 'fs';
import path from 'path';
import sharp from 'sharp';
import { pool } from '../config/database';

async function convertExistingImages() {
  console.log('🔄 Conversion et compression des images existantes en WebP...');
  const uploadsDir = path.join(__dirname, '../../../uploads/properties');

  if (!fs.existsSync(uploadsDir)) {
    console.log('Aucun dossier d\'upload trouvé.');
    process.exit(0);
  }

  const files = fs.readdirSync(uploadsDir);
  let convertedCount = 0;

  for (const file of files) {
    const ext = path.extname(file).toLowerCase();
    if (['.jpg', '.jpeg', '.png', '.bmp', '.tiff'].includes(ext)) {
      const oldPath = path.join(uploadsDir, file);
      const newFilename = file.substring(0, file.lastIndexOf('.')) + '.webp';
      const newPath = path.join(uploadsDir, newFilename);
      const oldRelativeUrl = `/uploads/properties/${file}`;
      const newRelativeUrl = `/uploads/properties/${newFilename}`;

      try {
        await sharp(oldPath)
          .resize(1920, 1080, { fit: 'inside', withoutEnlargement: true })
          .webp({ quality: 80, effort: 4 })
          .toFile(newPath);

        // Mettre à jour les références en BDD dans property_media
        await pool.query('UPDATE property_media SET url = ? WHERE url = ?', [newRelativeUrl, oldRelativeUrl]);

        // Supprimer l'ancienne image lourde non-webp
        fs.unlinkSync(oldPath);

        console.log(`✅ Converti : ${file} -> ${newFilename}`);
        convertedCount++;
      } catch (err: any) {
        console.error(`❌ Erreur conversion ${file} :`, err.message);
      }
    }
  }

  console.log(`🎉 Conversion terminée ! ${convertedCount} image(s) convertie(s) en WebP.`);
  process.exit(0);
}

convertExistingImages();
