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

// Create a new Truck
exports.createTruckType = async (req, res, next) => {
    try {
        const {
            logistics_id,
            truck_type,

        } = req.body;
  
        TruckType.create({
            logistics_id: logistics_id,
            truck_type: truck_type
        });
  
        res.status(201).json({ success: "Truck Type successfully created!" });
    } catch (err) {
        next(err);
    }
  };

   // Get all Trucks
exports.getAllTruckType = async (req, res, next) => {
    try {
      const trucktype = await TruckType.findAll();
  
      const trucktypeResponse = trucktype.map(truck_type = ({
            logistics_id,
            truck_type
     }) => ({
            logistics_id: logistics_id,
            truck_type: truck_type
     })
     
      );
      
      res.status(200).json(trucktypeResponse);
    } catch (error) {
      next(error)
    }
};

// Get Trucks by Id
exports.getTruckTypeId = async (req, res, next) => {
    const { TruckTypeId } = req.params;
  
    try {
      const trucktype = await TruckType.findByPk(TruckTypeId);
  
      if (!trucktype) {
        return res.status(404).json({ error: 'Truck Type not found' });
      }
  
      res.status(200).json(trucktype);
    } catch (error) {
        next(error)
    }
  };

  // Delete Truck Type
exports.deleteTruckTypeId = async (req, res, next) => {
    const { TruckTypeId } = req.params;
  
    try {
      const trucktype = await TruckType.findByPk(TruckTypeId);
  
      if (!trucktype) {
        return res.status(404).json({ error: 'Truck Type not found' });
      }
  
      await trucktype.destroy();
  
      res.status(201).json({ success: "The Truck Type ID has been successfully Deleted" });
    } catch (error) {
      next(error)
    }
  };

   // Update Truck by ID
exports.updateTruckType = async (req, res, next) => {
    const { TruckTypeId } = req.params;
    try {
      const trucktype = await TruckType.findByPk(TruckTypeId);
  
      if (!trucktype) {
        return res.status(404).json({ error: 'Truck Type not found' });
      }
  
      const { logistics_id, truck_type} = req.body;
  
      await trucktype.update({
            logistics_id,
            truck_type
      });
  
      res.status(200).json(trucktype);
    } catch (error) {
      next(error)
    }
  };
