const express = require("express");
const isAuth = require("../../../middlewares/authorization");
const computeDistance = require("../../../helpers/computeDistance");
const Customers = require("../../../models/Customers");
const Sellers = require("../../../models/Sellers");

const router = express.Router();

router.post("/calculate-distance", isAuth, (req, res) => {
  const { customerLat, customerLng, sellerId } = req.body;

  Sellers.findOne({ where: { seller_id: sellerId } })
    .then((seller) => {
      if (!seller) {
        return res.status(404).json({ error: 'Seller not found' });
      }

      return computeDistance(
        `${customerLat},${customerLng}`,
        `${seller.lat},${seller.long}`
      );
    })
    .then((distance) => {
      res.json({ distance });
    })
    .catch((error) => {
      console.error('Error calculating distance:', error.message);
      res.status(500).json({ error: 'Internal Server Error' });
    });
});

module.exports = router;
