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

// Create a new Driver
exports.createDriver = async (req, res, next) => {
    try {
        const {
            logistics_id,
            name,
            address,
            username,
            password
        } = req.body;
  
        Drivers.create({
            logistics_id: logistics_id,
            name: name,
            address: address,
            username: username,
            password: password,
        });
  
        res.status(201).json({ success: "Driver successfully created!" });
    } catch (err) {
        next(err);
    }
  };

  // Get all driver
exports.getDriver = async (req, res) => {
    try {
      const drivers = await Drivers.findAll();
  
      const driverResponse = drivers.map(voucher = ({
            logistics_id,
            name,
            address,
            username,
            password
     }) => ({

            logistics_id: logistics_id,
            name: name,
            address: address,
            username: username,
            password: password
     })
     
      );
      
      res.status(200).json(driverResponse);
    } catch (error) {
      console.error(error);
      res.status(500).json({ error: 'Internal Server Error' });
    }
};

// Get Driver by Id
exports.getDriverId = async (req, res) => {
    const { DriverId } = req.params;
  
    try {
      const driver = await Drivers.findByPk(DriverId);
  
      if (!driver) {
        return res.status(404).json({ error: 'Driver not found' });
      }
  
      res.status(200).json(driver);
    } catch (error) {
      console.error(error);
      res.status(500).json({ error: 'Internal Server Error' });
    }
  };

  // Delete Voucher
exports.deleteDriverId = async (req, res) => {
    const { DriverId } = req.params;
  
    try {
      const driver = await Drivers.findByPk(DriverId);
  
      if (!driver) {
        return res.status(404).json({ error: 'Driver not found' });
      }
  
      await driver.destroy();
  
      res.status(201).json({ success: "The Driver ID successfully Deleted" });
    } catch (error) {
      console.error(error);
      res.status(500).json({ error: 'Internal Server Error' });
    }
  };

  // Update Driver by ID
exports.updateDriverId = async (req, res) => {
    const { DriverId } = req.params;
    try {
      const driver = await Drivers.findByPk(DriverId);
  
      if (!driver) {
        return res.status(404).json({ error: 'Driver not found' });
      }
  
      const { logistics_id, name, address, username, password} = req.body;
  
      await driver.update({
            logistics_id,
            name,
            address,
            username,
            password
      });
  
      res.status(200).json(driver);
    } catch (error) {
      console.error(error);
      res.status(500).json({ error: 'Internal Server Error' });
    }
  };