const Settings = require('../models/Settings');
const asyncHandler = require('../middleware/async');
const ErrorResponse = require('../utils/errorResponse');

// @desc    Get settings
// @route   GET /api/v1/settings
// @access  Private/Admin
exports.getSettings = asyncHandler(async (req, res, next) => {
  let settings = await Settings.findOne();

  if (!settings) {
    // If no settings, create with defaults
    settings = await Settings.create({});
  }

  res.status(200).json({ success: true, data: settings });
});

// @desc    Create or Update settings
// @route   POST /api/v1/settings
// @access  Private/Admin
exports.updateSettings = asyncHandler(async (req, res, next) => {
  let settings = await Settings.findOne();

  if (settings) {
    settings = await Settings.findByIdAndUpdate(settings._id, req.body, {
      new: true,
      runValidators: true,
    });
  } else {
    settings = await Settings.create(req.body);
  }

  res.status(200).json({ success: true, data: settings });
});
