const multer = require('multer');

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',
	files: 'public/file-uploads',
};

const fileStorage = multer.diskStorage({
	destination: (req, file, cb) => {
		const uploadFolder = uploadFolders[file.fieldname] || 'public/uploads';
		cb(null, uploadFolder);
	},
	filename: (req, file, cb) => {
		const date = new Date();
		const formattedDate = date.toISOString().replace(/:/g, '-') + '-';
		cb(null, formattedDate + file.originalname);
	},
});

const fileFilter = (req, file, cb) => {
	if (
		file.mimetype === 'image/png' ||
		file.mimetype === 'image/jpg' ||
		file.mimetype === 'image/jpeg' ||
		file.mimetype === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || // DOCX
		file.mimetype === 'application/pdf'
	) {
		cb(null, true);
	} else {
		cb(new Error('File format not supported'), false);
	}
};

const multerConfig = (req, res, next) => {
	multer({
		storage: fileStorage,
		fileFilter: fileFilter,
		limits: {
			fileSize: 5 * 1024 * 1024, // 5MB
		},
	}).fields([
		{
			name: 'profileImg',
			maxCount: 1,
		},
		{
			name: 'coverImg',
			maxCount: 1,
		},
		{
			name: 'driverImg',
			maxCount: 1,
		},
		{
			name: 'vehicleImg',
			maxCount: 1,
		},
		{
			name: 'driverImg',
			maxCount: 1,
		},
		{
			name: 'vehicleImg',
			maxCount: 1,
		},
		{
			name: 'worldConTicketImg',
			maxCount: 1,
		},
		{
			name: 'postImgs',
			maxCount: 10,
		},
		{
			name: 'activityImgs',
			maxCount: 10,
		},
		{
			name: 'reviewImgs',
			maxCount: 10,
		},
		{
			name: 'eventImg',
			maxCount: 1,
		},
		{
			name: 'productImgs',
			maxCount: 10,
		},
		{
			name: 'hotelImgs',
			maxCount: 10,
		},
		{
			name: 'roomImgs',
			maxCount: 10,
		},
		{
			name: 'hotelReviewImgs',
			maxCount: 10,
		},
		{
			name: 'activityReviewImgs',
			maxCount: 10,
		},
		{
			name: 'restaurantImgs',
			maxCount: 10,
		},
		{
			name: 'restaurantReviewImgs',
			maxCount: 10,
		},
		{
			name: 'cocImg',
			maxCount: 1,
		},
		{ name: 'files', maxCount: 25 },
	])(req, res, next);
};

module.exports = multerConfig;
