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

exports.findAllOrders = (req, res, next) => {
  const { orderId, billingEmail } = req.query;

  const normalizedEmail = billingEmail ? billingEmail.replace(/%40/g, "@") : null;

  OrderForm.findOne({
    where: {
      reference_no: orderId,
      email: normalizedEmail,
    },
  })
    .then((order) => {
      if (!order) {
        return errorHandler(`Order ID does not exists! EMAIL: ${normalizedEmail}`, 404);
      }

      return Location.findAll({
        where: {
          order_id: orderId,
        },
        order: [["id", "DESC"]],
      });
    })
    .then((location) => {
      const trackOrder = location.map((location) => ({
        id: location.id,
        date: location.date,
        time: location.time,
        latitude: location.latitude,
        longitude: location.longtitude,
      }));
      return res.status(200).json({ success: true, trackOrder, email: normalizedEmail, reference_no: orderId });
    })
    .catch((err) => {
      next(err);
    });
};
