const jwt = require("jsonwebtoken");
const errorHandler = require("../util/errorHandler");
const Logistics = require("../models/Logistics");

// Create a Logistics
exports.createLogistics = async (req, res, next) => {
    try {
        const {
            company_name,
            address,
            owner,
            initial_username,
            intiial_password,
        } = req.body;
  
        Logistics.create({
            company_name: company_name,
            address: address,
            owner: owner,
            initial_username: initial_username,
            intiial_password: intiial_password,
        });
  
        res.status(201).json({ success: "Logistic successfully created!" });
    } catch (err) {
        next(err);
    }
  };

  // Get all Logistics
exports.getAllLogistics = async (req, res, next) => {
  try {
      const logistics = await Logistics.findAll();

      const logisticsResponse = logistics.map(logistic => ({
        id: logistic.id, 
        company_name: logistic.company_name,
          address: logistic.address,
          owner: logistic.owner,
          initial_username: logistic.initial_username,
          initial_password: logistic.initial_password
      }));

      res.status(200).json(logisticsResponse);
  } catch (error) {
      next(error);
  }
};

// Get Logistics by Id
exports.getLogisticsId = async (req, res, next) => {
    const { LogisticId } = req.params;
  
    try {
      const logistic = await Logistics.findByPk(LogisticId);
  
      if (!logistic) {
        return res.status(404).json({ error: 'Logistic not found' });
      }
  
      res.status(200).json(logistic);
    } catch (error) {
        next(error)
    }
  };

  // Delete Logistics
exports.deleteLogistics = async (req, res, next) => {
    const { LogisticId } = req.params;
  
    try {
      const logistic = await Logistics.findByPk(LogisticId);
  
      if (!logistic) {
        return res.status(404).json({ error: 'Logistic not found' });
      }
  
      await logistic.destroy();
  
      res.status(201).json({ success: "The Logistic ID has been successfully Deleted" });
    } catch (error) {
      next(error)
    }
  };

  // Update Logistic by ID
exports.updateLogistic = async (req, res, next) => {
    const { LogisticId } = req.params;
    try {
      const logistic = await Logistics.findByPk(LogisticId);
  
      if (!logistic) {
        return res.status(404).json({ error: 'Logistic not found' });
      }
  
      const { company_name, address, owner, initial_username, intiial_password} = req.body;
  
      await logistic.update({
            company_name,
            address,
            owner,
            initial_username,
            intiial_password,
      });
  
      res.status(200).json(logistic);
    } catch (error) {
      next(error)
    }
  };