const fs = require('fs'); const path = require('path'); const getNextImageNumber = () => { const uploadDir = path.join(__dirname, '../../frontend/public/images/products'); if (!fs.existsSync(uploadDir)) { fs.mkdirSync(uploadDir, { recursive: true }); return 43; } const files = fs.readdirSync(uploadDir); const numbers = files .filter(file => /^\d+\.(jpg|jpeg|png|webp|gif)$/i.test(file)) .map(file => parseInt(file.split('.')[0])) .filter(num => !isNaN(num)); return numbers.length > 0 ? Math.max(...numbers) + 1 : 43; }; const isValidImageFile = (filename) => { const validExtensions = ['.jpg', '.jpeg', '.png', '.webp', '.gif']; const ext = path.extname(filename).toLowerCase(); return validExtensions.includes(ext); }; const cleanupOldFiles = (daysOld = 30) => { const uploadDir = path.join(__dirname, '../../frontend/public/images/products'); if (!fs.existsSync(uploadDir)) { return; } const files = fs.readdirSync(uploadDir); const now = Date.now(); const cutoff = now - (daysOld * 24 * 60 * 60 * 1000); files.forEach(file => { const filePath = path.join(uploadDir, file); const stats = fs.statSync(filePath); if (stats.mtime.getTime() < cutoff && file.startsWith('temp-')) { fs.unlinkSync(filePath); console.log(`Cleaned up old file: ${file}`); } }); }; module.exports = { getNextImageNumber, isValidImageFile, cleanupOldFiles };