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

const productImportController = {
  create: async (req, res) => {
    try {
      const { product_id, productimport_amount, productimport_date, productimport_stats, productimport_remark } = req.body;

      const newProductImport = await ProductImport.create({
        product_id,
        productimport_amount,
        productimport_date,
        productimport_stats,
        productimport_remark,
      });

      res.status(201).json({
        message: 'Product import created successfully',
        data: newProductImport,
      });
    } catch (error) {
      res.status(500).json({ message: 'Failed to create product import', error: error.message });
    }
  },

  getAll: async (req, res) => {
    try {
      const productImports = await ProductImport.findAll();
      res.status(200).json(productImports);
    } catch (error) {
      res.status(500).json({ message: 'Failed to retrieve product imports', error: error.message });
    }
  },

  getById: async (req, res) => {
    try {
      const { id } = req.params;
      const productImport = await ProductImport.findByPk(id);

      if (!productImport) {
        return res.status(404).json({ message: 'Product import not found' });
      }

      res.status(200).json(productImport);
    } catch (error) {
      res.status(500).json({ message: 'Failed to retrieve product import', error: error.message });
    }
  },

  update: async (req, res) => {
    try {
      const { id } = req.params;
      const { product_id, productimport_amount, productimport_date, productimport_stats, productimport_remark } = req.body;

      const productImport = await ProductImport.findByPk(id);

      if (!productImport) {
        return res.status(404).json({ message: 'Product import not found' });
      }

      await productImport.update({
        product_id,
        productimport_amount,
        productimport_date,
        productimport_stats,
        productimport_remark,
      });

      res.status(200).json({
        message: 'Product import updated successfully',
        data: productImport,
      });
    } catch (error) {
      res.status(500).json({ message: 'Failed to update product import', error: error.message });
    }
  },

  delete: async (req, res) => {
    try {
      const { id } = req.params;

      const productImport = await ProductImport.findByPk(id);

      if (!productImport) {
        return res.status(404).json({ message: 'Product import not found' });
      }

      await productImport.destroy();

      res.status(200).json({ message: 'Product import deleted successfully' });
    } catch (error) {
      res.status(500).json({ message: 'Failed to delete product import', error: error.message });
    }
  },
};

module.exports = productImportController;
