const { splitSite } = require("../middlewares");
const db = require("../models");
const RoutePath = db.route_path;
const CenterPhone = db.center_phone;
const Employee = db.employee;
exports.createRoutePath = (req, res) => {
  // Validate request
  if (!req.body.name) {
    res.status(400).send({ message: "Content can not be empty!" });
    return;
  }
  const site = splitSite.findSiteNumber(req);
  // Create a Route
  const routePath = new RoutePath({
    name: req.body.name,
    schedule_date: req.body.schedule_date,
    vehicle: req.body.vehicle,
    status: req.body.status,
    driver: req.body.driver,
    type: req.body.type,
    start_mileage: req.body.start_mileage,
    end_mileage: req.body.end_mileage,
    start_time: req.body.start_time || null,
    end_time: req.body.end_time || null,
    estimated_start_time: req.body.estimated_start_time || null,
    route_customer_list: req.body.route_customer_list || [],
    checklist_result: req.body.checklist_result || [],
    site
  });
  // Save Route in the database
  routePath
    .save(routePath)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while creating the Route."
      });
    });
};
// Retrieve all Routes from the database.
exports.getAllRoutes = (req, res) => {
  var params = req.query;
  var condition = {};
  if (params) {
    if (params.scheduleDate) {
        condition.schedule_date = params.scheduleDate;
    }
    if (params.driverId) {
        condition.driver = params.driverId;
    }
  }
  condition.status = { "$ne": 'disabled' };
  condition = splitSite.splitSiteGet(req, condition);
  RoutePath.find(condition)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving Routes."
      });
    });
};

// Retrieve all Routes with phones from the database.
exports.getAllRoutesWithPhones = (req, res) => {
  var params = req.query;
  var condition = {};
  var condition2 = {};
  if (params) {
    if (params.scheduleDate) {
      condition.schedule_date = params.scheduleDate;
    }
    if (params.driverId) {
      condition.driver = params.driverId;
    }
    if (params.activated) {
      condition2.activated = params.activated
    }
  }
  condition.status = { "$ne": 'disabled' };
  condition = splitSite.splitSiteGet(req, condition);
  condition2 = splitSite.splitSiteGet(req, condition2);
  Promise.all(
    [RoutePath.find(condition), CenterPhone.find(condition2)]
  ).then(([transRoutes, phones]) => res.send({
    transRoutes: transRoutes,
    centerPhones: phones
  })).catch(err => {
    res.status(500).send({
      message:
        err.message || "Some error occurred while retrieving Routes or phones."
    });
  });
};

// Get One Route by Id
exports.getRoute = (req, res) => {
  const id = req.params.id;
  RoutePath.findById(id)
    .then(data => {
      if (!data)
        res.status(404).send({ message: "Not found Route with id " + id });
      else {
        // console.log('where is driver', data?.driver);
        // Employee.findByIdAndUpdate(driver, {fetch_route_time: new Date()}).then((rst) => {
        //     console.log('updated result',rst);
        // }).catch((err) => {
        //   console.log(`employee ${driver} update failure`)
        // })
        res.send(data);
      }
    })
    .catch(err => {
      res
        .status(500)
        .send({ message: "Error retrieving Route with id=" + id });
    });
};

// Update a Route by the id in the request
exports.updateRoute = (req, res) => {
  if (!req.body) {
    return res.status(400).send({
      message: "Data to update can not be empty!"
    });
  }
  const id = req.params.id;

  RoutePath.findById(id)
    .then((currentRoute) => {
      if (!currentRoute) {
        return res.status(404).send({
          message: `Cannot update Route with id=${id}. Maybe Route was not found!`
        });
      }

      const updatePayload = Object.assign({}, req.body);
      delete updatePayload.id;

      // Safety: only allow customer_route_status updates for customers that
      // already belong to this specific route id.
      if (Array.isArray(updatePayload.route_customer_list) && Array.isArray(currentRoute.route_customer_list)) {
        const customerIdsInCurrentRoute = new Set(
          currentRoute.route_customer_list.map((c) => `${c.customer_id || c._id || ''}`)
        );
        updatePayload.route_customer_list = updatePayload.route_customer_list.map((customer) => {
          const customerId = `${customer.customer_id || customer._id || ''}`;
          if (customer.customer_route_status && customerId && !customerIdsInCurrentRoute.has(customerId)) {
            const sanitizedCustomer = Object.assign({}, customer);
            delete sanitizedCustomer.customer_route_status;
            return sanitizedCustomer;
          }
          return customer;
        });
      }

      return RoutePath.findByIdAndUpdate(id, updatePayload, { useFindAndModify: false });
    })
    .then((data) => {
      if (!data) return;
      return res.send({ success: true, message: "Route was updated successfully." });
    })
    .catch(err => {
      res.status(500).send({
        success: false,
        message: "Error updating Route with id=" + id
      });
    });
};

// update route from mobile without deleting customers
exports.updateRouteInProgress = (req, res) => {
  if (!req.body) {
    res.status(400).send({ message: "Content can not be empty!" });
    return;
  }
  const routeBody = req.body;
  RoutePath.findById(routeBody.id)
    .then(data => {
      if (!data)
        res.status(404).send({ message: "Not found Route with id " + id });
      else {
          const currentRoute = data;
          const currentCustomerList = currentRoute.route_customer_list;
          const customerListSent = routeBody.route_customer_list;
          const finalCustomerList = [...customerListSent];
          for (const cust of currentCustomerList) {
              if (!customerListSent.find((c) => c.id === cust.id )) {
                  finalCustomerList.push(cust);
              }
          }
          let finalBody = {};
          if (finalCustomerList?.length > 0) {
            finalBody = Object.assign({}, routeBody, {route_customer_list: finalCustomerList})
          } else {
            const newBody = Object.assign({}, routeBody);
            delete newBody.route_customer_list;
            finalBody = Object.assign({}, newBody)
          } 
          RoutePath.findByIdAndUpdate(currentRoute.id, finalBody, { useFindAndModify: false })
            .then(data => {
              // console.log('success', data.id);
              // const driver = currentRoute?.driver;
              // if (driver) {
              //   Employee.findById(driver).then((data) => {
              //     const employeeObj = data;
              //     // console.log('driverOjb', employeeObj)
              //     if (employeeObj) {
              //       const update_route_history = employeeObj?.update_route_history;
              //       const newHistoryItem = {
              //         route_id: currentRoute?.id,
              //         route_name: currentRoute?.name,
              //         route_schedule_date: currentRoute?.schedule_date,
              //         route_update_time: new Date()
              //       };
              //       let result = [];
              //       if (update_route_history?.length >= 20) {
              //         for (let i=1; i < update_route_history.length; i++) {
              //           result.push(update_route_history[i]);
              //         }
              //         result.push(newHistoryItem);
              //       } else {
              //         update_route_history.push(newHistoryItem);
              //         result = update_route_history;
              //       }
              //       // console.log('final', result);
              //       Employee.findByIdAndUpdate(driver, Object.assign({}, employeeObj, {update_route_history: result})).then((rst) => {
              //           console.log('updated result',rst);
              //       }).catch((err) => {
              //         console.log(`employee ${driver} update failure`)
              //       })
              //     }
              //   })
              // }
              if (!data) {
                res.status(404).send({
                  message: `Cannot update Route with id=${id}. Maybe Route was not found!`
                });
              } else res.send({ success: true, message: "Route was updated successfully." });
            })
            .catch(err => {
              res.status(500).send({
                success: false,
                message: "Error updating Route with id=" + id
              });
            });
            
        // res.send({ success: true, message: "Route was found successfully." });
      }
    })
    .catch(err => {
      res
        .status(500)
        .send({ message: "Error retrieving Route with id=" + id });
    });
}

// Delete a Route by id
exports.deleteRoute= (req, res) => {
  const id = req.params.id;
  RoutePath.findByIdAndRemove(id)
    .then(data => {
      if (!data) {
        res.status(404).send({
          message: `Cannot delete Route with id=${id}. Maybe Route was not found!`
        });
      } else {
        res.send({
          message: "Route was deleted successfully!"
        });
      }
    })
    .catch(err => {
      res.status(500).send({
        message: "Could not delete Route with id=" + id
      });
    });
};

// Get all routes on and after today
exports.getAllRoutesOnAndAfterToday = (req, res) => {
  const today = new Date();
  const todayString = `${String(today.getMonth() + 1).padStart(2, '0')}/${String(today.getDate()).padStart(2, '0')}/${today.getFullYear()}`;
  
  var condition = {
    status: { "$ne": 'disabled' }
  };
  condition = splitSite.splitSiteGet(req, condition);
  
  RoutePath.find(condition)
    .then(data => {
      // Filter routes with schedule_date on or after today
      const filteredRoutes = data.filter(route => {
        if (!route.schedule_date) return false;
        
        // Convert MM/DD/YYYY to Date object for comparison
        const [month, day, year] = route.schedule_date.split('/');
        const routeDate = new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
        
        // Set today's time to start of day for fair comparison
        const todayStart = new Date(today.getFullYear(), today.getMonth(), today.getDate());
        
        return routeDate >= todayStart;
      });
      
      res.send(filteredRoutes);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving Routes."
      });
    });
};
