const supplierModel = require('../models/supplierModel');
const { autoUpdateSupplierTotals } = require('../helpers/supplierHelper');

// Create Supplier
exports.createSupplier = async (req, res) => {
  try {
      const supplierId = await supplierModel.createSupplier(req.body);
      res.json({ success: true, message: 'Supplier created.', supplierId });
  } catch (err) {
      res.status(500).json({ error: err.message });
  }
};

// Update Supplier
exports.updateSupplier = async (req, res) => {
  const supplier_id = req.params.id;
  try {
      const supplier = await supplierModel.getSupplierById(supplier_id);
      if (!supplier) return res.status(404).json({ error: 'Supplier not found.' });

      await supplierModel.updateSupplier(supplier_id, req.body);
      res.json({ success: true, message: 'Supplier updated.' });
  } catch (err) {
      res.status(500).json({ error: err.message });
  }
};

exports.getAllSuppliers = async (req, res) => {
  const { search } = req.query;

  try {
      const suppliers = await supplierModel.listSuppliers(search);
      res.json(suppliers);
  } catch (err) {
      console.error('Fetch Suppliers Error:', err);
      res.status(500).json({ error: err.message });
  }
};

exports.getSupplierById = async (req, res) => {
  const supplier_id = req.params.id;

  try {
      const supplier = await supplierModel.getSupplierByIdWithTotals(supplier_id);
      if (!supplier) return res.status(404).json({ error: 'Supplier not found.' });

      res.json(supplier);
  } catch (err) {
      res.status(500).json({ error: err.message });
  }
};

// Delete Supplier
exports.deleteSupplier = async (req, res) => {
  const supplier_id = req.params.id;
  try {
      const supplier = await supplierModel.getSupplierById(supplier_id);
      if (!supplier) return res.status(404).json({ error: 'Supplier not found.' });

      await supplierModel.deleteSupplier(supplier_id);
      res.json({ success: true, message: 'Supplier deleted (soft delete).' });
  } catch (err) {
      res.status(500).json({ error: err.message });
  }
};

// Manually Trigger Payment Totals Update
exports.updateSupplierTotals = async (req, res) => {
  const supplier_id = req.params.id;
  try {
      await supplierModel.updateSupplierTotals(supplier_id);
      res.json({ success: true, message: 'Supplier totals updated.' });
  } catch (err) {
      res.status(500).json({ error: err.message });
  }
};

exports.getSupplierPaymentHistory = async (req, res) => {
  const supplier_id = req.params.id;

  try {
      const payments = await supplierModel.getSupplierPaymentHistory(supplier_id);
      res.json({
          supplier_id,
          payment_count: payments.length,
          payment_history: payments
      });
  } catch (err) {
      res.status(500).json({ error: err.message });
  }
};
