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

const uploadFolders = {
	profileImg: 'public/profile-uploads',
	coverImg: 'public/profile-uploads',
	driverImg: 'public/driver-uploads',
	vehicleImg: 'public/driver-uploads',
	worldConTicketImg: 'public/world-con-tickets-uploads',
	postImgs: 'public/post-uploads',
	activityImgs: 'public/activity-uploads',
	activityReviewImgs: 'public/activity-uploads',
	reviewImgs: 'public/activity-uploads',
	eventImg: 'public/event-uploads',
	productImgs: 'public/product-uploads',
	reviewImages: 'public/hotel-uploads',
	hotelImgs: 'public/hotel-uploads',
	roomImgs: 'public/hotel-uploads',
	hotelReviewImgs: 'public/hotel-uploads',
	restaurantImgs: 'public/restaurant-uploads',
	restaurantReviewImgs: 'public/restaurant-uploads',
	cocImg: 'public/coc-uploads',
};

const deleteFile = require('../../helpers/delete-file');

exports.uploadFiles = async (req, res, next) => {
	try {
		const files = req.files?.files;
		if (!Array.isArray(files) || files.length === 0) {
			return res.status(400).json({ success: false, error: 'No files uploaded' });
		}

		const acceptedFiles = [];
		const rejectedFiles = [];

		for (const file of files) {
			if (file.fieldname === 'files') {
				acceptedFiles.push(file.filename);
			} else {
				await deleteFile(file.path);
				rejectedFiles.push(file.filename);
			}
		}

		res.json({ success: true, filenames: acceptedFiles, rejected: rejectedFiles });
	} catch (error) {
		next(error);
	}
};

exports.moveFiles = async (req, res, next) => {
	try {
		const { destination, filenames } = req.body;
		const allowedDestinations = Object.values(uploadFolders).map((folder) => folder.replace(/^public\//, ''));

		if (
			!destination ||
			!allowedDestinations.includes(destination) ||
			!Array.isArray(filenames) ||
			filenames.length === 0
		) {
			return res.status(400).json({
				success: false,
				error:
					'Valid destination and filenames are required. Destination must be one of: ' + allowedDestinations.join(', '),
			});
		}

		const movedFiles = [];
		for (const filename of filenames) {
			const sourcePath = path.join('public', 'file-uploads', filename);
			const destPath = path.join('public', destination, filename);

			if (!sourcePath.startsWith(path.join('public')) || !destPath.startsWith(path.join('public'))) {
				movedFiles.push({ success: false, filename, message: 'error', error: 'Invalid file path' });
				continue;
			}

			try {
				await fs.promises.rename(sourcePath, destPath);
				movedFiles.push({ success: true, filename, message: 'moved' });
			} catch (err) {
				movedFiles.push({ success: false, filename, message: 'error', error: err.message });
			}
		}

		res.json({ movedFiles, success: true, destination });
	} catch (error) {
		next(error);
	}
};

exports.deleteFiles = async (req, res, next) => {
	try {
		const { destination, filenames } = req.body;
		const allowedDestinations = [
			...Object.values(uploadFolders).map((folder) => folder.replace(/^public\//, '')),
			'file-uploads',
		];

		if (
			!destination ||
			!allowedDestinations.includes(destination) ||
			!Array.isArray(filenames) ||
			filenames.length === 0
		) {
			return res.status(400).json({
				success: false,
				error:
					'Valid destination and filenames are required. Destination must be one of: ' + allowedDestinations.join(', '),
			});
		}

		const deletedFiles = [];
		for (const filename of filenames) {
			try {
				await deleteFile(filename, destination);
				deletedFiles.push({ success: true, filename });
			} catch (err) {
				deletedFiles.push({ success: false, filename, error: err.message });
			}
		}

		res.json({ deletedFiles, success: true, destination });
	} catch (error) {
		next(error);
	}
};
