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

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

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

  const data = {};

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

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

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

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

    const data = {};

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

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

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

const flagCols = {
  stayfinder_latest_features: 'stayfinderLatestFeatures',
  stayfinder_latest_features_email: 'stayfinderLatestFeaturesEmail',
  stayfinder_latest_features_message: 'stayfinderLatestFeaturesMessage',
  travel_advice: 'travelAdvice',
  travel_advice_email: 'travelAdviceEmail',
  travel_advice_message: 'travelAdviceMessage',
  account_management_and_guidelines: 'accountManagementAndGuidelines',
  account_management_and_guidelines_email: 'accountManagementAndGuidelinesEmail',
  account_management_and_guidelines_message: 'accountManagementAndGuidelinesMessage',
  travelers_and_host_messages: 'travelersAndHostMessages',
  travelers_and_host_messages_email: 'travelersAndHostMessagesEmail',
  travelers_and_host_messages_message: 'travelersAndHostMessagesMessage',
};
