#!/usr/bin/env node

/**
 * Cleanup Script for Orphaned Upload Files
 * 
 * This script removes temporary upload files that were not deleted after
 * being uploaded to cloud storage.
 * 
 * Usage:
 *   node scripts/cleanupOrphanedUploads.js
 * 
 * Options:
 *   --dry-run    Show what would be deleted without actually deleting
 *   --older-than Number of hours (default: 1) - only delete files older than this
 */

const fs = require('fs');
const path = require('path');

const args = process.argv.slice(2);
const isDryRun = args.includes('--dry-run');
const olderThanIndex = args.indexOf('--older-than');
const olderThanHours = olderThanIndex !== -1 ? parseInt(args[olderThanIndex + 1]) || 1 : 1;

const uploadsDir = path.join(__dirname, '../public/uploads');

console.log('🧹 Cleanup Orphaned Upload Files');
console.log('================================');
console.log(`Directory: ${uploadsDir}`);
console.log(`Mode: ${isDryRun ? 'DRY RUN (no files will be deleted)' : 'LIVE'}`);
console.log(`Filter: Files older than ${olderThanHours} hour(s)`);
console.log('');

if (!fs.existsSync(uploadsDir)) {
    console.error('❌ Uploads directory not found!');
    process.exit(1);
}

const files = fs.readdirSync(uploadsDir);
const now = Date.now();
const cutoffTime = now - (olderThanHours * 60 * 60 * 1000);

let deletedCount = 0;
let skippedCount = 0;
let totalSize = 0;

// Patterns for temporary upload files (multer naming convention)
const tempFilePattern = /^(logo|favicon|ogImage|twitterImage|promoBannerImage|offerBannerImage\d+)-\d+-\d+\.(png|jpg|jpeg|gif|webp|avif|svg)$/;

files.forEach(file => {
    const filePath = path.join(uploadsDir, file);
    const stats = fs.statSync(filePath);
    
    // Skip directories
    if (stats.isDirectory()) {
        return;
    }
    
    // Check if file matches temp upload pattern
    if (!tempFilePattern.test(file)) {
        return;
    }
    
    // Check file age
    if (stats.mtimeMs > cutoffTime) {
        skippedCount++;
        console.log(`⏭️  Skipped (too recent): ${file} (${formatSize(stats.size)})`);
        return;
    }
    
    totalSize += stats.size;
    
    if (isDryRun) {
        console.log(`🗑️  Would delete: ${file} (${formatSize(stats.size)})`);
        deletedCount++;
    } else {
        try {
            fs.unlinkSync(filePath);
            console.log(`✅ Deleted: ${file} (${formatSize(stats.size)})`);
            deletedCount++;
        } catch (err) {
            console.error(`❌ Failed to delete ${file}:`, err.message);
        }
    }
});

console.log('');
console.log('Summary');
console.log('=======');
console.log(`${isDryRun ? 'Would delete' : 'Deleted'}: ${deletedCount} file(s)`);
console.log(`Skipped: ${skippedCount} file(s)`);
console.log(`Total size: ${formatSize(totalSize)}`);

if (isDryRun && deletedCount > 0) {
    console.log('');
    console.log('💡 Run without --dry-run to actually delete these files');
}

function formatSize(bytes) {
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
    return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
}
