const Info = require("../models/infoModel");

// @desc    Get the company info
// @route   GET /api/v1/info
// @access  Public
exports.getInfo = async (req, res, next) => {
  try {
    // Find the first document (assuming singleton pattern)
    const info = await Info.findOne();

    res.status(200).json({
      status: "success",
      data: {
        info,
      },
    });
  } catch (err) {
    res.status(500).json({
      status: "error",
      message: err.message,
    });
  }
};

// @desc    Create info (Run this only once)
// @route   POST /api/v1/info
// @access  Private (Admin)
exports.createInfo = async (req, res, next) => {
  try {
    const newInfo = await Info.create(req.body);

    res.status(201).json({
      status: "success",
      data: {
        info: newInfo,
      },
    });
  } catch (err) {
    res.status(400).json({
      status: "fail",
      message: err.message,
    });
  }
};

// @desc    Update info
// @route   PATCH /api/v1/info/:id
// @access  Private (Admin)
exports.updateInfo = async (req, res, next) => {
  try {
    // We can update by ID or just update the first found document
    const info = await Info.findByIdAndUpdate(req.params.id, req.body, {
      new: true,
      runValidators: true,
    });

    if (!info) {
      return res
        .status(404)
        .json({ status: "fail", message: "No info found with that ID" });
    }

    res.status(200).json({
      status: "success",
      data: {
        info,
      },
    });
  } catch (err) {
    res.status(400).json({
      status: "fail",
      message: err.message,
    });
  }
};

// @desc    Delete info
// @route   DELETE /api/v1/info/:id
// @access  Private (Admin)
exports.deleteInfo = async (req, res, next) => {
  try {
    const info = await Info.findByIdAndDelete(req.params.id);

    if (!info) {
      return res
        .status(404)
        .json({ status: "fail", message: "No info found with that ID" });
    }

    res.status(204).json({
      status: "success",
      data: null,
    });
  } catch (err) {
    res.status(400).json({
      status: "fail",
      message: err.message,
    });
  }
};
