const fs = require('fs');
const path = require('path');
const cron = require('node-cron');

const UPLOAD_DIR = path.join(__dirname, '../public/file-uploads');
const RETENTION_HOURS = 24;

function getTimestampFromFilename(filename) {
	const match = filename.match(/^([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}-[0-9]{2}-[0-9]{2}\.\d{3}Z)-/);
	if (!match) return null;
	let iso = match[1].replace(/-/g, ':').replace(/\.(\d{3})Z/, '.$1Z');
	iso = iso.replace(/T(\d{2}):(\d{2}):(\d{2})\.(\d{3})Z/, (m, h, m2, s, ms) => `T${h}:${m2}:${s}.${ms}Z`);
	iso = iso.replace(/T(\d{2}):(\d{2}):(\d{2})\.(\d{3})Z/, (m, h, m2, s, ms) => `T${h}:${m2}:${s}.${ms}Z`);
	try {
		return new Date(iso);
	} catch {
		return null;
	}
}

function deleteOldFiles() {
	fs.readdir(UPLOAD_DIR, (err, files) => {
		if (err) return;
		const now = Date.now();
		files.forEach((filename) => {
			const timestamp = getTimestampFromFilename(filename);
			if (!timestamp) return;
			const ageHours = (now - timestamp.getTime()) / (1000 * 60 * 60);
			if (ageHours > RETENTION_HOURS) {
				const filePath = path.join(UPLOAD_DIR, filename);
				fs.unlink(filePath, (err) => {
					if (!err) {
						console.log(`Deleted old temp file: ${filename}`);
					}
				});
			}
		});
	});
}

cron.schedule('0 * * * *', () => {
	console.log('Running temp file cleanup...');
	deleteOldFiles();
});

if (require.main === module) {
	deleteOldFiles();
}
