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

// Create a new Driver
exports.createLocation = async (req, res, next) => {
  try {
    const { vehicle_id, order_id, date, time, latitude, longtitude } = req.body;

    await Location.create({
      vehicle_id: vehicle_id,
      order_id: order_id,
      date: date,
      time: time,
      latitude: latitude,
      longtitude: longtitude,
    });

    res.status(201).json({ success: "Location successfully created!" });
  } catch (err) {
    next(err);
  }
};

// Get all Location
exports.getAllLocation = async (req, res, next) => {
  try {
    const locations = await Location.findAll();

    const locationResponse = locations.map(
      (location = ({
        vehicle_id,
        order_id,
        date,
        time,
        latitude,
        longtitude,
      }) => ({
        vehicle_id: vehicle_id,
        order_id: order_id,
        date: date,
        time: time,
        latitude: latitude,
        longtitude: longtitude,
      }))
    );

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

// Get Location by Id
exports.getLocationId = async (req, res, next) => {
  const { LocationId } = req.params;

  try {
    const location = await Location.findByPk(LocationId);

    if (!location) {
      return res.status(404).json({ error: "Location not found" });
    }

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

// Delete Location
exports.deleteLocation = async (req, res, next) => {
  const { LocationId } = req.params;

  try {
    const location = await Location.findByPk(LocationId);

    if (!location) {
      return res.status(404).json({ error: "Logistic not found" });
    }

    await location.destroy();

    res
      .status(201)
      .json({ success: "The Location ID has been successfully Deleted" });
  } catch (error) {
    next(error);
  }
};

// Update Location by ID
exports.updateLocation = async (req, res, next) => {
  const { LocationId } = req.params;
  try {
    const location = await Location.findByPk(LocationId);

    if (!location) {
      return res.status(404).json({ error: "Location not found" });
    }

    const { vehicle_id, order_id, date, time, latitude, longtitude } = req.body;

    await location.update({
      vehicle_id,
      order_id,
      date,
      time,
      latitude,
      longtitude,
    });

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