const { UsersPrivacyFlags } = require('../../models');

exports.getPrivacyFlags = async (req, res) => {
	const { userId } = req;

	const userFlags = await UsersPrivacyFlags.findOne({
		where: {
			user_id: userId,
		},
		attributes: {
			exclude: ['id', 'user_id'],
		},
	});

	const data = {};

	for (const [key, value] of Object.entries(privacyFlagCols)) {
		data[value] = userFlags[key];
	}

	return res.status(200).json({
		success: true,
		data: data ?? null,
	});
};

exports.updatePrivacyFlags = async (req, res, next) => {
	try {
		const { userId } = req;

		const userFlags = await UsersPrivacyFlags.findOne({
			where: {
				user_id: userId,
			},
		});

		const data = {};

		for (const [key, value] of Object.entries(privacyFlagCols)) {
			if (req.body[value] !== undefined) {
				data[key] = req.body[value];
			}
		}

		if (userFlags) {
			await userFlags.update(data);
		} else {
			await UsersPrivacyFlags.create({
				user_id: userId,
				...data,
			});
		}

		return res.status(200).json({
			success: true,
			message: 'Flags updated successfully',
		});
	} catch (error) {
		next(error);
	}
};

const privacyFlagCols = {
	read_receipts: 'readReceipts',
	view_my_on_listings: 'viewMyOnListings',
	display_my_location: 'displayMyLocation',
	display_trip_details: 'displayTripDetails',
	display_duration_of_visit: 'displayDurationOfVisit',
};
