const { deleteFile } = require('../helpers');

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

exports.deleteUploadedFiles = (req) => {
	for (const key in req.files) {
		if (req.files[key] && req.files[key].length > 0) {
			for (const file of req.files[key]) {
				deleteFile(file.filename, uploadFolders[key]);
			}
		}
	}
};

exports.deleteFiles = async (files, key = 'image', path = 'file-uploads') => {
	try {
		if (!files || (!Array.isArray(files) && typeof files !== 'object' && typeof files !== 'string')) {
			throw new Error('Invalid files argument');
		}

		let filenames = [];

		if (typeof files === 'string') {
			filenames = [files];
		} else if (Array.isArray(files)) {
			if (files.length && typeof files[0] === 'object' && files[0] !== null) {
				filenames = files.map((f) => f[key]).filter(Boolean);
			} else {
				filenames = files.filter(Boolean);
			}
		} else if (typeof files === 'object') {
			if (files[key]) filenames = [files[key]];
		}

		await Promise.all(filenames.map((filename) => deleteFile(filename, path)));
		console.log('Files deleted successfully:', filenames);
	} catch (error) {
		console.error('Error deleting files:', error);
	}
};

const http = require('http');

const FILE_SERVER_URL = process.env.FILE_SERVER_URL;
const FILES_API_KEY = process.env.FILES_API_KEY;

exports.deleteUploadedFilesFromFileServer = async (req) => {
	try {
		const destination = 'public/file-uploads';
		let filenames = [];

		for (const key in uploadFolders) {
			if (req.body.hasOwnProperty(key)) {
				const value = req.body[key];
				if (Array.isArray(value)) {
					filenames.push(...value);
				} else if (typeof value === 'string' && value.trim() !== '') {
					filenames.push(value);
				}
			}
		}

		if (!filenames.length) {
			console.error('No filenames provided for deletion');
			return;
		}

		const data = JSON.stringify({ filenames, destination });

		const url = new URL(FILE_SERVER_URL);
		const options = {
			hostname: url.hostname,
			port: url.port || 80,
			path: url.pathname,
			method: 'DELETE',
			headers: {
				'Content-Type': 'application/json',
				'Content-Length': Buffer.byteLength(data),
				'x-api-key': FILES_API_KEY,
			},
		};

		const request = http.request(options, (response) => {
			let responseData = '';
			response.on('data', (chunk) => {
				responseData += chunk;
			});
			response.on('end', () => {
				if (response.statusCode === 200) {
					console.log('Files deleted successfully:', filenames);
				} else {
					console.error('Failed to delete files:', responseData);
				}
			});
		});

		request.on('error', (err) => {
			console.error('Error deleting files:', err);
		});

		request.write(data);
		request.end();
	} catch (error) {
		console.error('Error deleting files from file server:', error);
	}
};

exports.deleteFilesFromFileServer = async (filenames, destination = 'file-uploads') => {
	try {
		if (!filenames.length) {
			console.error('No filenames provided for deletion');
			return;
		}

		const data = JSON.stringify({ filenames, destination });

		const url = new URL(FILE_SERVER_URL);
		const options = {
			hostname: url.hostname,
			port: url.port || 80,
			path: url.pathname,
			method: 'DELETE',
			headers: {
				'Content-Type': 'application/json',
				'Content-Length': Buffer.byteLength(data),
				'x-api-key': FILES_API_KEY,
			},
		};

		const request = http.request(options, (response) => {
			let responseData = '';
			response.on('data', (chunk) => {
				responseData += chunk;
			});
			response.on('end', () => {
				if (response.statusCode === 200) {
					console.log('Files deleted successfully:', filenames);
				} else {
					console.error('Failed to delete files:', responseData);
				}
			});
		});

		request.on('error', (err) => {
			console.error('Error deleting files:', err);
		});

		request.write(data);
		request.end();
	} catch (error) {
		console.error('Error deleting files from file server:', error);
	}
};

exports.moveFilesFromFileServer = async (filenames, destination) => {
	try {
		if (!filenames.length) {
			console.error('No filenames provided for moving');
			return;
		}

		const data = JSON.stringify({ filenames, destination });

		const url = new URL(FILE_SERVER_URL);
		const options = {
			hostname: url.hostname,
			port: url.port || 80,
			path: url.pathname,
			method: 'PATCH',
			headers: {
				'Content-Type': 'application/json',
				'Content-Length': Buffer.byteLength(data),
				'x-api-key': FILES_API_KEY,
			},
		};

		const request = http.request(options, (response) => {
			let responseData = '';
			response.on('data', (chunk) => {
				responseData += chunk;
			});
			response.on('end', () => {
				if (response.statusCode === 200) {
					console.log('Files moved successfully:', filenames);
				} else {
					console.error('Failed to move files:', responseData);
				}
			});
		});

		request.on('error', (err) => {
			console.error('Error deleting files:', err);
		});

		request.write(data);
		request.end();
	} catch (error) {
		console.error('Error deleting files from file server:', error);
	}
};
