const CreditLimit = require("../models/CreditLimit");
const jwt = require("jsonwebtoken");
const errorHandler = require("../util/errorHandler");
const multer = require('multer');
// Create a new product

exports.createCreditLimit = (req, res, next) => {
  const {data } = req.body;
    const {
        credit_limit, 
    } = data;

    if (!credit_limit) {
        return errorHandler("Credit_limit is missing from the request.", 400);
    }

    CreditLimit.findOne({ 
        where: {
            credit_limit: credit_limit,
        },
    })
    .then((creditlimit) => {
        if (creditlimit) {
            return errorHandler("CreditLimit ID already exists!", 401 );
        }
        
        return new CreditLimit({
            credit_limit: credit_limit, 
        }).save();
    })
    .then(() => {
        res.status(201).json({ success: true });
    })
    .catch((err) => {
        next(err);
    });
};

// Update a product by ID
  exports.updateCreditLimitID =  (req, res) => {
    const { CreditlimitID } = req.params; // id
    const { data } = req.body;
    const { 
      credit_limit, 
    } = data;
  
    CreditLimit.findOne ({
        where:{
            id: CreditlimitID,
              },
    })
    .then ((creditlimit) => {
        if(!creditlimit) {
            return errorHandler("CreditLimit ID does not exists!", 404);
        }
        creditlimit.credit_limit = credit_limit
        return creditlimit.save();
    })
    .then(() => {
        res.status(200).json({ success: true });
    })
  };
  


// Get all products
exports.getAllCreditLimit = async (req, res) => {
  try {
    const credlimit = await CreditLimit.findAll({
      order: [['credit_limit', 'ASC']]
    });

    const credlimitresponse = credlimit.map(product = ({
      credit_limit,
   }) => ({
    credit_limit: credit_limit,
   })
   
   );
   res.status(200).json(credlimitresponse);
  }
   catch (error) {
    console.error(error);
    res.status(500).json({ error: "Internal Server Error" });
  }
};

// Get a specific product by ID
exports.getCreditLimitById =  async (req, res) => {
  const { CreditlimitID } = req.params;

  try {
    const credlimit = await CreditLimit.findByPk(CreditlimitID);

    if (!credlimit) {
      return res.status(404).json({ error: "CreditLimit not found" });
    }

    res.status(200).json(credlimit);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Internal Server Error" });
  }
};


// Delete a product by ID
exports.deleteCreditlimitById = (req, res) => {
  const { CreditlimitID } = req.params;

  try {
    const deletedRowCount = CreditLimit.destroy({
      where: {
        id: CreditlimitID,
      },
    });

    if (deletedRowCount === 0) {
      return res.status(404).json({ error: "CreditLimit not found" });
    }

    res.status(204).send();
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Internal Server Error" });
  }
};
