const model = require('../Model/index');  // Make sure the model is correctly imported
const { ObjectId } = require("mongodb");
const NodeCache = require('node-cache');
const axios = require('axios');

 


// Controller to save an array of vehicles
const saveVehicles = async (req, res) => {
    try {
        // Extract the array of vehicles from the request body
        const vehicles = req.body;

        // Check if the request body is an array
        if (!Array.isArray(vehicles)) {
            return res.status(400).json({ message: "Input data should be an array of vehicle objects." });
        }

        // Save all the vehicles to the database
        const savedVehicles = await model.CurrentBits.insertMany(vehicles);

        // Return a success response with the saved data
        return res.status(201).json({
            message: 'Vehicles saved successfully',
            data: savedVehicles
        });
    } catch (error) {
        // Return an error response in case of failure
        console.error(error);
        return res.status(500).json({
            message: 'An error occurred while saving vehicles',
            error: error.message
        });
    }
}
// const getVehicles = async (req, res) => {
//     try {
//         console.log("req query: " + JSON.stringify(req.query.UserId));

//         let query = {};
//         if (req.query.carsFilters && Object.keys(req.query.carsFilters).length > 0) {
//             const { year_from, year_to, vehicle_type, make, model, odometer_max, odometer_min, price_max, price_min, start_code, transmission, auction_type, cylinders, drive_type, color } = req.query.carsFilters;

//             if (year_from) query.year = { ...query.year, $gte: parseInt(year_from) };
//             if (year_to) query.year = { ...query.year, $lte: parseInt(year_to) };
//             if (odometer_min) query.odometer = { ...query.odometer, $gte: parseInt(odometer_min) };
//             if (odometer_max) query.odometer = { ...query.odometer, $lte: parseInt(odometer_max) };
//             if (price_min) query.cost_priced = { ...query.cost_priced, $gte: parseInt(price_min) };
//             if (price_max) query.cost_priced = { ...query.cost_priced, $lte: parseInt(price_max) };

//             if (vehicle_type && vehicle_type !== 'All') query.vehicle_type = vehicle_type;
//             if (start_code && start_code !== 'All') query.status = start_code;
//             if (transmission && transmission !== 'All') query.transmission = transmission;
//             if (auction_type && auction_type !== 'All') query.base_site = auction_type;
//             if (cylinders && cylinders !== 'All') query.cylinders = cylinders;
//             if (drive_type && drive_type !== 'All') query.drive = drive_type;
//             if (color && color !== 'All') query.color = color;
//             if (make) query.make = make;
//             if (model) query.model = model;
//         }

//         // Pagination setup
//         let { page } = req.query;
//         page = parseInt(page) || 1;
//         const limit = 5;
//         const skip = (page - 1) * limit;

//         // Determine userId
//         let userId = req.query.UserId || req.params.UserId || req.body.userId;

//         console.log("Received userId:", userId);

//         // If no userId is provided, fetch superadmin's userId
//         if (!userId) {
//             const superAdmin = await model.User.findOne({ role: "superadmin" });
//             if (!superAdmin) {
//                 return res.status(404).json({ message: "Superadmin not found" });
//             }
//             userId = superAdmin._id.toString();
//             console.log("Using Superadmin userId:", userId);
//         }

//         // Validate and convert userId to ObjectId
//         if (!ObjectId.isValid(userId.trim())) {
//             return res.status(400).json({ error: "Invalid User ID" });
//         }
//         userId = new ObjectId(userId.trim());

//         // Find user in the database
//         const Role = await model.User.findOne({ _id: userId });
//         console.log("User role:", Role?.role);

//         if (!Role) {
//             const superAdmin = await model.User.findOne({ role: "superadmin" });
//             if (superAdmin) {
//                 userId = superAdmin._id.toString();
//             } else {
//                 return res.status(404).json({ message: "Superadmin not found" });
//             }
//         } 
//         else if (Role.role === "admin") {
//             userId = Role._id.toString();
//         } 
//         else if (Role.role === "user") {
//             userId = Role.AdminId;
//             const user = await model.User.findOne({ _id: userId });

//             if (user && user.AdminId) {
//                 userId = user.AdminId.toString();
//             }
//             console.log("User's Admin ID found:", userId);
//         }

//         // Fetch paginated vehicles
//         const totalVehicles = await model.CurrentBits.countDocuments(query);
//         const vehiclesData = await model.CurrentBits.find(query).skip(skip).limit(limit);

//         // Process each vehicle to add pricing
//         const vehicles = await Promise.all(vehiclesData.map(async (vehicle) => {
//             const vehicleObj = vehicle.toObject();

//             // Skip if no location
//             if (!vehicle.location) {
//                 return vehicleObj;
//             }

//             // Extract State and City from location
//             const [State, City] = vehicle.location.split("-").map(loc => loc.trim());

//             // Clean city name by removing directional words
//             const directionKeywords = ["NORTH", "EAST", "WEST", "SOUTH"];
//             const cleanedCity = City.toUpperCase()
//                 .split(" ")
//                 .filter(word => !directionKeywords.includes(word))
//                 .join(" ");

//             // Find location data
//             const locationData = await model.location.findOne({ 
//                 City: cleanedCity, 
//                 userId 
//             });
//             console.log("Location Data:", locationData);

//             if (!locationData) {
//                 return vehicleObj; // Return vehicle without prices if location not found
//             }

//             const locationId = locationData._id;

//             // Find location pricing
//             let locationPricing = await model.LocationPricing.findOne({
//                 userId,
//                 locationId
//             });

//             console.log("Location Pricing:", locationPricing);

//             // Fallback to superadmin pricing if no specific pricing found
//             if (!locationPricing) {
//                 const superAdmin = await model.User.findOne({ role: "superadmin" });
//                 if (superAdmin) {
//                     locationPricing = await model.LocationPricing.findOne({
//                         userId: superAdmin._id,
//                         locationId
//                     });
//                 }
//             }

//             // Add pricing and location details to vehicle object
//             if (locationPricing) {
//                 vehicleObj.City = locationData.City;
//                 vehicleObj.State = locationData.State;
//                 vehicleObj.Price1 = locationPricing.Price1;
//                 vehicleObj.Price2 = locationPricing.Price2;
//                 vehicleObj.Price3 = locationPricing.Price3;
//             }

//             return vehicleObj;
//         }));

//         // Return response
//         return res.status(200).json({
//             message: 'Vehicles fetched successfully',
//             page,
//             limit,
//             totalPages: Math.ceil(totalVehicles / limit),
//             totalVehicles,
//             data: vehicles
//         });

//     } catch (error) {
//         console.error(error);
//         return res.status(500).json({
//             message: 'An error occurred while fetching vehicles',
//             error: error.message
//         });
//     }
// };
const getVehicles = async (req, res) => {
    try {
        console.log("req query: " + JSON.stringify(req.query));

        let query = {};
        if (req.query.carsFilters && Object.keys(req.query.carsFilters).length > 0) {
            const { year_from, year_to, vehicle_type, make, model, odometer_max, odometer_min, price_max, price_min, start_code, transmission, auction_type, cylinders, drive_type, color } = req.query.carsFilters;

            if (year_from) query.year = { ...query.year, $gte: parseInt(year_from) };
            if (year_to) query.year = { ...query.year, $lte: parseInt(year_to) };
            if (odometer_min) query.odometer = { ...query.odometer, $gte: parseInt(odometer_min) };
            if (odometer_max) query.odometer = { ...query.odometer, $lte: parseInt(odometer_max) };
            if (price_min) query.cost_priced = { ...query.cost_priced, $gte: parseInt(price_min) };
            if (price_max) query.cost_priced = { ...query.cost_priced, $lte: parseInt(price_max) };

            if (vehicle_type && vehicle_type !== 'All') query.vehicle_type = vehicle_type;
            if (start_code && start_code !== 'All') query.status = start_code;
            if (transmission && transmission !== 'All') query.transmission = transmission;
            if (auction_type && auction_type !== 'All') query.base_site = auction_type;
            if (cylinders && cylinders !== 'All') query.cylinders = cylinders;
            if (drive_type && drive_type !== 'All') query.drive = drive_type;
            if (color && color !== 'All') query.color = color;
            if (make) query.make = make;
            if (model) query.model = model;
        }

        // Pagination setup
        let { page } = req.query;
        page = parseInt(page) || 1;
        const limit = 5;
        const skip = (page - 1) * limit;

        // Determine userId
        let userId;
        console.log("req user is", req.query.UserId);
 
        if (!req.query.UserId) {
            const superAdmin = await model.User.findOne({ role: "superadmin" });
            if (superAdmin) {
                userId = superAdmin._id.toString();
            } else {
                return res.status(404).json({ message: "Superadmin not found" });
            }
        } else {
            const user = await model.User.findById(req.query.UserId);
            if (!user) {
                return res.status(404).json({ message: "User not found" });
            }

            // If role is admin, return their own _id
            if (user.role === "admin") {
                userId = user._id;
            } else {
                userId = user.AdminId;        
            }
        }

        // Fetch paginated vehicles
        const totalVehicles = await model.CurrentBits.countDocuments(query);
        const vehiclesData = await model.CurrentBits.find(query).skip(skip).limit(limit);

        // Process each vehicle to add pricing and location details
        const vehicles = await Promise.all(vehiclesData.map(async (vehicle) => {
            const vehicleObj = vehicle.toObject();
            console.log("vehicle location, ", vehicleObj);

            // Skip if no location
            if (!vehicle.location) {
                return vehicleObj;
            }

            // Extract State and City from location
            const [State, City] = vehicle.location.split("-").map(loc => loc.trim());

            // Clean city name by removing directional words
            const directionKeywords = ["NORTH", "EAST", "WEST", "SOUTH"];
            const cleanedCity = City.toUpperCase()
                .split(" ")
                .filter(word => !directionKeywords.includes(word))
                .join(" ");

            // Find location data
            const locationData = await model.location.findOne({ 
                City: cleanedCity,
                userId
            });
            console.log("location de");
            

            if (!locationData) {
                return vehicleObj; // Return vehicle without prices or location details if location not found
            }

            const locationId = locationData._id;

            // Find location pricing
            let locationPricing = await model.LocationPricing.findOne({
                userId,
                locationId
            });

            // Fallback to superadmin pricing if no specific pricing found
            if (!locationPricing) {
                const superAdmin = await model.User.findOne({ role: "superadmin" });
                if (superAdmin) {
                    locationPricing = await model.LocationPricing.findOne({
                        userId: superAdmin._id,
                        locationId
                    });
                }
            }

            // Add pricing and location details to vehicle object
            if (locationPricing) {
                vehicleObj.City = locationData.City;
                vehicleObj.State = locationData.State;
                vehicleObj.Port1 = locationData.Port1 || "N/A";
                vehicleObj.Port2 = locationData.Port2 || "N/A";
                vehicleObj.Price1 = locationPricing.Price1;
                vehicleObj.Price2 = locationPricing.Price2;
                vehicleObj.Price3 = locationPricing.Price3;
            }

            return vehicleObj;
        })); 
        console.log("vehicle detail ", vehicles);

        // Return response
        return res.status(200).json({
            message: 'Vehicles fetched successfully',
            page,
            limit,
            totalPages: Math.ceil(totalVehicles / limit),
            totalVehicles,
            data: vehicles
        });

    } catch (error) {
        console.error(error);
        return res.status(500).json({
            message: 'An error occurred while fetching vehicles',
            error: error.message
        });
    }
};




// const getVehicles = async (req, res) => {
//     try {
//         console.log("req query: " + JSON.stringify(req.query.UserId));

//         let query = {};
//         if (req.query.carsFilters && Object.keys(req.query.carsFilters).length > 0) {
//             const { year_from, year_to, vehicle_type, make, model, odometer_max, odometer_min, price_max, price_min, start_code, transmission, auction_type, cylinders, drive_type, color } = req.query.carsFilters;

//             if (year_from) query.year = { ...query.year, $gte: parseInt(year_from) };
//             if (year_to) query.year = { ...query.year, $lte: parseInt(year_to) };
//             if (odometer_min) query.odometer = { ...query.odometer, $gte: parseInt(odometer_min) };
//             if (odometer_max) query.odometer = { ...query.odometer, $lte: parseInt(odometer_max) };
//             if (price_min) query.cost_priced = { ...query.cost_priced, $gte: parseInt(price_min) };
//             if (price_max) query.cost_priced = { ...query.cost_priced, $lte: parseInt(price_max) };

//             if (vehicle_type && vehicle_type !== 'All') query.vehicle_type = vehicle_type;
//             if (start_code && start_code !== 'All') query.status = start_code;
//             if (transmission && transmission !== 'All') query.transmission = transmission;
//             if (auction_type && auction_type !== 'All') query.base_site = auction_type;
//             if (cylinders && cylinders !== 'All') query.cylinders = cylinders;
//             if (drive_type && drive_type !== 'All') query.drive = drive_type;
//             if (color && color !== 'All') query.color = color;
//             if (make) query.make = make;
//             if (model) query.model = model;
//         }

//         // Pagination setup
//         let { page } = req.query;
//         page = parseInt(page) || 1;
//         const limit = 5;
//         const skip = (page - 1) * limit;

//         // Determine userId
//         let userId = req.query.UserId || req.params.UserId || req.body.userId;
//         let finalUserId;
        
//         if (userId && ObjectId.isValid(userId.trim())) {
//             userId = new ObjectId(userId.trim());
//             const user = await model.User.findOne({ _id: userId });
            
//             if (user) {
//                 if (user.role === 'admin') {
//                     finalUserId = user._id;
//                 } else if (user.role === 'user' && user.AdminId) {
//                     finalUserId = user.AdminId;
//                 }
//             }
//         }
        
//         // If no valid userId or user not found, use superadmin
//         if (!finalUserId) {
//             console.log("no  admin get ");
            
//             const superAdmin = await model.User.findOne({ role: "superadmin" });
//             // if (superAdmin) {
//             //     finalUserId = superAdmin._id;
//             // }
//             //  else {
//             //     return res.status(404).json({ message: "Superadmin not found" });
//             // }
//         }

//         console.log("Final userId:", finalUserId);

//         // Fetch paginated vehicles
//         const totalVehicles = await model.CurrentBits.countDocuments(query);
//         const vehiclesData = await model.CurrentBits.find(query).skip(skip).limit(limit);

//         // Process each vehicle to add pricing
//         const vehicles = await Promise.all(vehiclesData.map(async (vehicle) => {
//             const vehicleObj = vehicle.toObject();

//             if (!vehicle.location) {
//                 return vehicleObj;
//             }

//             // Extract State and City from location
//             const [State, City] = vehicle.location.split("-").map(loc => loc.trim());

//             // Clean city name
//             const directionKeywords = ["NORTH", "EAST", "WEST", "SOUTH"];
//             const cleanedCity = City.toUpperCase()
//                 .split(" ")
//                 .filter(word => !directionKeywords.includes(word))
//                 .join(" ");

//             // Find location data
//             const locationData = await model.location.findOne({ City: cleanedCity });
            
//             if (!locationData) {
//                 return vehicleObj;
//             }

//             const locationId = locationData._id;

//             // Try to find pricing with finalUserId first (admin or user's admin)
//             let locationPricing = await model.LocationPricing.findOne({
//                 userId: finalUserId,
//                 locationId
//             });

//             // If no pricing found and finalUserId isn't superadmin, try superadmin
//             // if (!locationPricing && finalUserId.toString() !== (await model.User.findOne({ role: "superadmin" }))._id.toString()) {
//             //     const superAdmin = await model.User.findOne({ role: "superadmin" });
//             //     if (superAdmin) {
//             //         locationPricing = await model.LocationPricing.findOne({
//             //             userId: superAdmin._id,
//             //             locationId
//             //         });
//             //     }
//             // }
//             // console.log("loc");
            

//             // Add pricing and location details to vehicle object
//             if (locationPricing) {
//                 vehicleObj.City = locationData.City;
//                 vehicleObj.State = locationData.State;
//                 vehicleObj.Price1 = locationPricing.Price1;
//                 vehicleObj.Price2 = locationPricing.Price2;
//                 vehicleObj.Price3 = locationPricing.Price3;
//             }

//             return vehicleObj;
//         }));

//         // Return response
//         return res.status(200).json({
//             message: 'Vehicles fetched successfully',
//             page,
//             limit,
//             totalPages: Math.ceil(totalVehicles / limit),
//             totalVehicles,
//             data: vehicles
//         });

//     } catch (error) {
//         console.error(error);
//         return res.status(500).json({
//             message: 'An error occurred while fetching vehicles',
//             error: error.message
//         });
//     }
// };

// const getVehicles = async (req, res) => {
//     try {
//         console.log("req query: " + JSON.stringify(req.query.UserId));
             
//         let query = {};
//         if (req.query.carsFilters && Object.keys(req.query.carsFilters).length > 0) {
//             const { year_from, year_to, vehicle_type, make, model, odometer_max, odometer_min, price_max, price_min, start_code, transmission, auction_type, cylinders, drive_type, color } = req.query.carsFilters;

//             if (year_from) query.year = { ...query.year, $gte: parseInt(year_from) };
//             if (year_to) query.year = { ...query.year, $lte: parseInt(year_to) };
//             if (odometer_min) query.odometer = { ...query.odometer, $gte: parseInt(odometer_min) };
//             if (odometer_max) query.odometer = { ...query.odometer, $lte: parseInt(odometer_max) };
//             if (price_min) query.cost_priced = { ...query.cost_priced, $gte: parseInt(price_min) };
//             if (price_max) query.cost_priced = { ...query.cost_priced, $lte: parseInt(price_max) };

//             if (vehicle_type && vehicle_type !== 'All') query.vehicle_type = vehicle_type;
//             if (start_code && start_code !== 'All') query.status = start_code;
//             if (transmission && transmission !== 'All') query.transmission = transmission;
//             if (auction_type && auction_type !== 'All') query.base_site = auction_type;
//             if (cylinders && cylinders !== 'All') query.cylinders = cylinders;
//             if (drive_type && drive_type !== 'All') query.drive = drive_type;
//             if (color && color !== 'All') query.color = color;
//             if (make) query.make = make;
//             if (model) query.model = model;
//         }

//         // Pagination setup
//         let { page } = req.query;
//         page = parseInt(page) || 1;
//         const limit = 5;
//         const skip = (page - 1) * limit;

//         // Determine userId
//         let userId = req.query.UserId || req.params.UserId || req.body.userId;
//         console.log("Received userId:", userId);
        
//         // Validate userId
//         if (!userId || !ObjectId.isValid(userId.trim())) {
//             res.status(400).json({ error: "Invalid User ID" });
//             return;
//         }
        
//         // Convert userId to ObjectId
//         userId = new ObjectId(userId.trim());
        
//         // Find user in the database
//         const Role = await model.User.findOne({ _id: userId });
//         console.log("role is", Role?.role);
        
//         if (!Role) {
//             return res.status(404).json({ message: "User not found" });
//         } 
//         else if(Role.role === "admin") {
//             userId = Role.id;
//         }
//         else if(Role.role === "user") {
//             userId = Role.AdminId;
//             const user = await model.User.findOne({ where: { id: userId } });

//             if (user && user.AdminId) {
//                 userId = user.AdminId;
//             }
//             console.log("Using admin id for pricing:", userId);
//         }

//         // Fetch paginated vehicles
//         const totalVehicles = await model.CurrentBits.countDocuments(query);
//         const vehiclesData = await model.CurrentBits.find(query).skip(skip).limit(limit);

//         // Process each vehicle to add pricing
//         const vehicles = await Promise.all(vehiclesData.map(async (vehicle) => {
//             const vehicleObj = vehicle.toObject();

//             // Skip if no location
//             if (!vehicle.location) {
//                 return vehicleObj;
//             }

//             // Extract State and City from location
//             const [State, City] = vehicle.location.split("-").map(loc => loc.trim());

//             // Clean city name by removing directional words
//             const directionKeywords = ["NORTH", "EAST", "WEST", "SOUTH"];
//             const cleanedCity = City.toUpperCase()
//                 .split(" ")
//                 .filter(word => !directionKeywords.includes(word))
//                 .join(" ");

//             // Find location data
//             const locationData = await model.location.findOne({ 
//                 City: cleanedCity 
//             });

//             if (!locationData) {
//                 console.log(`No location data found for: ${City}, ${State}`);
//                 return vehicleObj;
//             }

//             const locationId = locationData._id;

//             // Find location pricing ONLY for the admin (no superadmin fallback)
//             const locationPricing = await model.LocationPricing.findOne({
//                 userId,
//                 locationId
//             });
           
//             if (locationPricing) {
//                 console.log(`Admin pricing found for: ${locationData.City}, ${locationData.State}`);
//                 console.log(`Admin ID: ${userId}`);
//                 console.log(`Prices: Price1=${locationPricing.Price1}, Price2=${locationPricing.Price2}, Price3=${locationPricing.Price3}`);

//                 vehicleObj.City = locationData.City;
//                 vehicleObj.State = locationData.State;
//                 vehicleObj.Price1 = locationPricing.Price1;
//                 vehicleObj.Price2 = locationPricing.Price2;
//                 vehicleObj.Price3 = locationPricing.Price3;
//             } else {
//                 console.log(`No admin pricing found for: ${locationData.City}, ${locationData.State}`);
//             }

//             return vehicleObj;
//         }));

//         // Return response
//         return res.status(200).json({
//             message: 'Vehicles fetched successfully',
//             page,
//             limit,
//             totalPages: Math.ceil(totalVehicles / limit),
//             totalVehicles,
//             data: vehicles
//         });

//     } catch (error) {
//         console.error(error);
//         return res.status(500).json({
//             message: 'An error occurred while fetching vehicles',
//             error: error.message
//         });
//     }
// };

// const getVehicles = async (req, res) => {
//     try {
//         console.log("req query: " + JSON.stringify(req.query.UserId));

//         let query = {};
//         if (req.query.carsFilters && Object.keys(req.query.carsFilters).length > 0) {
//             const { year_from, year_to, vehicle_type, make, model, odometer_max, odometer_min, price_max, price_min, start_code, transmission, auction_type, cylinders, drive_type, color } = req.query.carsFilters;

//             if (year_from) query.year = { ...query.year, $gte: parseInt(year_from) };
//             if (year_to) query.year = { ...query.year, $lte: parseInt(year_to) };
//             if (odometer_min) query.odometer = { ...query.odometer, $gte: parseInt(odometer_min) };
//             if (odometer_max) query.odometer = { ...query.odometer, $lte: parseInt(odometer_max) };
//             if (price_min) query.cost_priced = { ...query.cost_priced, $gte: parseInt(price_min) };
//             if (price_max) query.cost_priced = { ...query.cost_priced, $lte: parseInt(price_max) };

//             if (vehicle_type && vehicle_type !== 'All') query.vehicle_type = vehicle_type;
//             if (start_code && start_code !== 'All') query.status = start_code;
//             if (transmission && transmission !== 'All') query.transmission = transmission;
//             if (auction_type && auction_type !== 'All') query.base_site = auction_type;
//             if (cylinders && cylinders !== 'All') query.cylinders = cylinders;
//             if (drive_type && drive_type !== 'All') query.drive = drive_type;
//             if (color && color !== 'All') query.color = color;
//             if (make) query.make = make;
//             if (model) query.model = model;
//         }

//         // Pagination setup
//         let { page } = req.query;
//         page = parseInt(page) || 1;
//         const limit = 5;
//         const skip = (page - 1) * limit;

//         // Determine userId
//         let userId = req.query.UserId || req.params.UserId || req.body.userId;
//         let finalUserId;
        
//         if (userId && ObjectId.isValid(userId.trim())) {
//             userId = new ObjectId(userId.trim());
//             const user = await model.User.findOne({ _id: userId });
            
//             if (user) {
//                 if (user.role === 'admin') {
//                     finalUserId = user._id;
//                 } else if (user.role === 'user' && user.AdminId) {
//                     finalUserId = user.AdminId;
//                 }
//             }
//         }
        
//         // If no valid userId or user not found, use superadmin
//         if (!finalUserId) {
//             console.log("no  admin get ");
            
//             const superAdmin = await model.User.findOne({ role: "superadmin" });
//             // if (superAdmin) {
//             //     finalUserId = superAdmin._id;
//             // }
//             //  else {
//             //     return res.status(404).json({ message: "Superadmin not found" });
//             // }
//         }

//         console.log("Final userId:", finalUserId);

//         // Fetch paginated vehicles
//         const totalVehicles = await model.CurrentBits.countDocuments(query);
//         const vehiclesData = await model.CurrentBits.find(query).skip(skip).limit(limit);

//         // Process each vehicle to add pricing
//         const vehicles = await Promise.all(vehiclesData.map(async (vehicle) => {
           
//         }));

//         // Return response
//         return res.status(200).json({
//             message: 'Vehicles fetched successfully',
//             page,
//             limit,
//             totalPages: Math.ceil(totalVehicles / limit),
//             totalVehicles,
//             data: vehicles
//         });

//     } catch (error) {
//         console.error(error);
//         return res.status(500).json({
//             message: 'An error occurred while fetching vehicles',
//             error: error.message
//         });
//     }
// };



// const getVehicles = async (req, res) => {
//     try {
//         let query = {};
//         if (req.query.carsFilters && Object.keys(req.query.carsFilters).length > 0) {
//             const { year_from, year_to, vehicle_type, make, model, odometer_max, odometer_min, price_max, price_min, start_code, transmission, auction_type, cylinders, drive_type, color } = req.query.carsFilters;

//             if (year_from) query.year = { ...query.year, $gte: parseInt(year_from) };
//             if (year_to) query.year = { ...query.year, $lte: parseInt(year_to) };
//             if (odometer_min) query.odometer = { ...query.odometer, $gte: parseInt(odometer_min) };
//             if (odometer_max) query.odometer = { ...query.odometer, $lte: parseInt(odometer_max) };
//             if (price_min) query.cost_priced = { ...query.cost_priced, $gte: parseInt(price_min) };
//             if (price_max) query.cost_priced = { ...query.cost_priced, $lte: parseInt(price_max) };

//             if (vehicle_type && vehicle_type !== 'All') query.vehicle_type = vehicle_type;
//             if (start_code && start_code !== 'All') query.status = start_code;
//             if (transmission && transmission !== 'All') query.transmission = transmission;
//             if (auction_type && auction_type !== 'All') query.base_site = auction_type;
//             if (cylinders && cylinders !== 'All') query.cylinders = cylinders;
//             if (drive_type && drive_type !== 'All') query.drive = drive_type;
//             if (color && color !== 'All') query.color = color;
//             if (make) query.make = make;
//             if (model) query.model = model;
//         }

//         let { page } = req.query;
//         page = parseInt(page) || 1;
//         const limit = 5;
//         const skip = (page - 1) * limit;

//         const totalVehicles = await model.CurrentBits.countDocuments(query);
//         const vehicles = await model.CurrentBits.find(query).skip(skip).limit(limit);

//         const keywordToRemove = ['North', 'East', 'West', 'South'];

//         // 🔴 FIX: Change forEach to for...of
//         for (const vehicle of vehicles) {
//             if (vehicle.location) {
//                 let [state, ...cityParts] = vehicle.location.split(' '); // Split into state & city
//                 let city = cityParts.join(' '); // Recombine city parts

//                 // Remove directional words from city
//                 keywordToRemove.forEach(word => {
//                     city = city.replace(new RegExp(`\\b${word}\\b`, 'gi'), '').replace(/^-|\s+$/g, '').trim();
//                 });

//                 city = city.toUpperCase(); // Convert city to uppercase

//                 console.log(`State: ${state}, City: ${city}`);

//                 // Query the location collection
//                 const locations = await model.location.find({ City: city });
//                 console.log("location deatil is now", locations[0]._id);
                
//                 const userId = '675b4cbbf8afd11631f028e7';
//                 const locationId='67e1d9d036a7c418ea87f109';
//                 const pricing_detial = await model.LocationPricing.find({ 
//                     userId, locationId });
//                     console.log("pricing detial ", pricing_detial);
                    
//             }
//         }
        
        
//         // const locations = await model.location.find({ City: city });
       
        
//         return res.status(200).json({
//             message: 'Vehicles fetched successfully',
//             page,
//             limit,
//             totalPages: Math.ceil(totalVehicles / limit),
//             totalVehicles,
//             data: vehicles
//         });
//     } catch (error) {
//         console.error(error);
//         return res.status(500).json({
//             message: 'An error occurred while fetching vehicles',
//             error: error.message
//         });
//     }
// };

// const axios = require('axios');
// const NodeCache = require('node-cache');

// const NodeCache = require("node-cache");
// const axios = require("axios");
const apiCache = new NodeCache({ stdTTL: 60 * 5 }); // Cache TTL: 5 minutes
const requestQueue = [];
const requestTimestamps = [];

const MAX_REQUESTS_PER_SECOND = 2;

function generateCacheKey(params) {
  return Object.entries(params)
    .sort(([a], [b]) => a.localeCompare(b))
    .map(([key, value]) => {
      if (Array.isArray(value)) {
        return `${key}=${value.sort().join(",")}`;
      }
      return `${key}=${value}`;
    })
    .join("&");
}

setInterval(processQueue, 200);

async function processQueue() {
  const now = Date.now();

  while (requestTimestamps.length > 0 && now - requestTimestamps[0] > 1000) {
    requestTimestamps.shift();
  }

  while (requestQueue.length > 0 && requestTimestamps.length < MAX_REQUESTS_PER_SECOND) {
    const { req, res, params, apiKey, cacheKey } = requestQueue.shift();

    console.log("Processing queued request...", { cacheKey, params, size: params.size });

    requestTimestamps.push(Date.now());

    try {
      const response = await axios.get("https://api.apicar.store/api/cars", {
        params: { ...params, size: Number(params.size) },
        headers: { "api-key": apiKey },
      });

      console.log("External API response:", {
        size: response.data.size,
        count: response.data.count,
        dataLength: response.data.data?.length,
        page: response.data.page,
        pages: response.data.pages,
      });

      const vehicleData = Array.isArray(response.data.data) ? response.data.data : [];

      // const superAdmin = await model.User.findOne({ role: "superadmin" });
      // let userId = superAdmin ? superAdmin._id.toString() : null;

    const processedVehicles = await Promise.all(
  vehicleData.map(async (vehicle) => {
    const vehicleObj = { ...vehicle };

    if (!vehicleObj.location) {
      return vehicleObj;
    }

    let City = null;
    let State = null;

    // Handle both formats: "Bakersfield (CA)" and "CA - Bakersfield"
    if (vehicleObj.location.includes("(")) {
      // Format: "Bakersfield (CA)"
      const locationMatch = vehicleObj.location.match(/^(.+?)\s*\((.+?)\)$/);
      City = locationMatch ? locationMatch[1].trim() || null : null;
      State = locationMatch ? locationMatch[2].trim() || null : null;
    } else if (vehicleObj.location.includes("-")) {
      // Format: "CA - Bakersfield"
      const [statePart, ...cityParts] = vehicleObj.location.split("-").map(part => part.trim());
      State = statePart || null;
      City = cityParts.join(" ") || null;
    } else {
      console.warn(`Invalid location format: "${vehicleObj.location}"`);
      vehicleObj.State = null;
      vehicleObj.City = null;
      return vehicleObj;
    }

    if (!City || !State) {
      console.warn(`Invalid location format: "${vehicleObj.location}"`);
      vehicleObj.State = State;
      vehicleObj.City = null;
      return vehicleObj;
    }

    const directionKeywords = ["NORTH", "EAST", "WEST", "SOUTH"];
    const cleanedCity = City.toUpperCase()
      .split(" ")
      .filter((word) => !directionKeywords.includes(word.toUpperCase()))
      .join(" ")
      .trim();
      let userId;
      let markup;
if (req.query.id) {
  const user = await model.User.findById(req.query.id);
  if (!user) {
    throw new Error("User not found for provided ID");
  }
  if (user.role === "admin" || user.role === "superadmin") {
    userId = user._id.toString();
    console.log("admin is logined", userId);
    
  } else if (user.role === "user") {
    userId = user.AdminId ? user.AdminId.toString() : null;
    markup=user.markup
    if (!userId) {
      throw new Error("AdminId not found for user");
    }
  } else {
    throw new Error("Invalid user role");
  }
} else {
  const superAdmin = await model.User.findOne({ role: "superadmin" });
  if (!superAdmin) {
    throw new Error("Superadmin not found");
  }
  userId = superAdmin._id.toString();
}
       
       
// if(req.user.role=="admin"){
//    userId= req.user.id
// }
// else{
//  const superAdmin = await model.User.findOne({ role: "superadmin" });
//      userId = superAdmin ? superAdmin._id.toString() : null;
// }
   
console.log("user id iss ", userId,cleanedCity);

    const locationData = await model.location.findOne({
      City: cleanedCity,
      userId,
    });
console.log("location data NOW ", locationData);

    if (!locationData) {
      vehicleObj.State = State;
      vehicleObj.City = cleanedCity;
      return vehicleObj;
    }

    const locationId = locationData._id;
    // log("id and location", userId, locationId)
    const locationPricing = await model.LocationPricing.findOne({
      userId,
      locationId,
    });

console.log("locationprinng is   ", locationPricing);

    vehicleObj.City = locationData.City;
    vehicleObj.State = locationData.State;
     vehicleObj.Port1 = locationData.Port1;
      vehicleObj.Port2 = locationData.Port2;
      vehicleObj.markup= markup||0

    if (locationPricing) {
      vehicleObj.Price1 = locationPricing.Price1;
      vehicleObj.Price2 = locationPricing.Price2;
      vehicleObj.Price3 = locationPricing.Price3;
      // vehicleObj.Port1 = locationPricing.Port1;
      // vehicleObj.Port2 = locationPricing.Port2;
    }
    // console.log("vehicleObj is no  ", vehicleObj);
    

    return vehicleObj;
  })
);

      const processedData = {
        size: Number(response.data.size) || params.size,
        page: response.data.page,
        pages: response.data.pages,
        count: response.data.count,
        data: processedVehicles,
      };

      const cacheSetSuccess = apiCache.set(cacheKey, processedData);
      // console.log("data procesed is ",  processedData);
      
      console.log("Cache set:", {
        cacheKey,
        success: cacheSetSuccess,
        dataLength: processedData.data.length,
      });

      res.json({
        source: "api",
        data: processedData,
      });
    } catch (error) {
      console.error("API Error:", {
        message: error.message,
        status: error.response?.status,
        cacheKey,
      });
      res.status(500).json({
        error: "Failed to fetch car data",
        details: error.message,
      });
    }
  }
}

const getCars = async (req, res) => {
  console.log("req query", req.query.id);
  
  try {
    const {
      make,
      model,
      site,
      buy_now,
      transmission,
      fuel,
      status,
      drive,
      damage_pr,
      engine,
      document,
      year_from,
      year_to,
      odometer_min,
      odometer_max,
      sort,
      direction,
      page,
      size,
      lot,
    } = req.query;


    console.log("Received query:", { size, page, transmission, fuel });

    const apiKey = "1f14a9d6-14e2-49b6-bc12-fd881b5a3e08";
    if (!apiKey) {
      return res.status(400).json({ error: "API key is required in headers" });
    }

    const params = {
      make,
      model,
      site,
      buy_now,
      transmission: transmission ? transmission.split(",") : undefined,
      fuel: fuel ? fuel.split(",") : undefined,
      status: status ? status.split(",") : undefined,
      drive: drive ? drive.split(",") : undefined,
      damage_pr: damage_pr ? damage_pr.split(",") : undefined,
      engine: engine ? engine.split(",") : undefined,
      document: document ? document.split(",") : undefined,
      year_from,
      year_to,
      odometer_min,
      odometer_max,
      sort,
      direction,
      page,
      size,
    };

    const numericParams = [
      "year_from",
      "year_to",
      "odometer_min",
      "odometer_max",
      "size",
      "page",
    ];

    numericParams.forEach((param) => {
      if (params[param]) {
        params[param] = Number(params[param]);
      }
    });

    Object.keys(params).forEach((key) => {
      if (
        params[key] === undefined ||
        params[key] === "" ||
        params[key] === "All" ||
        (Array.isArray(params[key]) && params[key].length === 0)
      ) {
        delete params[key];
      }
    });

    const cacheKey = generateCacheKey(params);
    const cachedData = apiCache.get(cacheKey);
    console.log("Cache check:", {
      cacheKey,
      cachedData: cachedData ? "found" : "not found",
      params,
    });

    // if (cachedData) {
    //   console.log("Serving from cache");
    //   return res.json({
    //     source: "cache",
    //     data: cachedData,
    //   });
    // }

    console.log(`Request queued (${requestQueue.length + 1} in queue)`);
    requestQueue.push({ req, res, params, apiKey, cacheKey });
  } catch (error) {
    console.error("Route Error:", { message: error.message, stack: error.stack });
    res.status(500).json({
      error: "Failed to fetch car data",
      details: error.message,
    });
  }
};
const getCarByVin = async (req, res) => {
  try {
    const { lot } = req.params;

    // Validate input
    if (!lot) {
      return res.status(400).json({ message: 'Lot number or VIN is required' });
    }

    let response;
    const apiKey = '1f14a9d6-14e2-49b6-bc12-fd881b5a3e08';

    // Check if input length is <= 8 (lot number) or > 8 (VIN)
    if (lot.length <= 8) {
      // Call API for lot number
      response = await axios.get(`https://api.apicar.store/api/cars/${lot}`, {
        headers: {
          'api-key': apiKey,
        },
      });
    } else {
      // Call API for VIN
      response = await axios.get(`https://api.apicar.store/api/cars/vin/all`, {
        headers: {
          'api-key': apiKey,
        },
        params: {
          vin: lot,
        },
      });
    }

    // Normalize response: if response.data is an array, return the first item; otherwise, return as is
    const responseData = Array.isArray(response.data) ? response.data[0] || {} : response.data;

    // Return the normalized response data
    res.status(200).json(responseData);
  } catch (error) {
    console.error('Error fetching car data:', error.message);
    res.status(500).json({
      message: 'Failed to fetch car data',
      error: error.response?.data?.message || error.message,
    });
  }
};





// const vinApiCache = new NodeCache({ stdTTL: 60 * 5 }); // Cache TTL: 5 minutes
// const vinRequestQueue = [];
// const vinRequestTimestamps = [];

// const MAX_VIN_REQUESTS_PER_SECOND = 2;

// function generateVinCacheKey(params) {
//   return Object.entries(params)
//     .sort(([a], [b]) => a.localeCompare(b))
//     .map(([key, value]) => {
//       if (Array.isArray(value)) {
//         return `${key}=${value.sort().join(",")}`;
//       }
//       return `${key}=${value}`;
//     })
//     .join("&");
// }

// setInterval(processVinQueue, 200);

// async function processVinQueue() {
//   const now = Date.now();

//   while (vinRequestTimestamps.length > 0 && now - vinRequestTimestamps[0] > 1000) {
//     vinRequestTimestamps.shift();
//   }

//   while (vinRequestQueue.length > 0 && vinRequestTimestamps.length < MAX_VIN_REQUESTS_PER_SECOND) {
//     const { req, res, params, apiKey, cacheKey } = vinRequestQueue.shift();

//     console.log("Processing queued VIN request...", { cacheKey, params });

//     vinRequestTimestamps.push(Date.now());

//     try {
//       let response;
//       if (params.lot.length <= 8) {
//         // Call API for lot number
//         response = await axios.get(`https://api.apicar.store/api/cars/${params.lot}`, {
//           headers: { "api-key": apiKey },
//         });
//         // Normalize to array format
//         response.data = response.data ? [response.data] : [];
//       } else {
//         // Call API for VIN
//         response = await axios.get(`https://api.apicar.store/api/cars/vin/all`, {
//           headers: { "api-key": apiKey },
//           params: { vin: params.lot },
//         });
//         // Ensure data is array
//         response.data = Array.isArray(response.data) ? response.data : (response.data ? [response.data] : []);
//       }

//       console.log("External VIN API response:", {
//         dataLength: response.data.length,
//         lot: params.lot
//       });

//       const processedVehicles = await Promise.all(
//         response.data.map(async (vehicle) => {
//           const vehicleObj = { ...vehicle };

//           // Skip processing if no location
//           if (!vehicleObj.location) {
//             return vehicleObj;
//           }

//           // Parse location (same as bulk API)
//           let City = null;
//           let State = null;
          
//           if (vehicleObj.location.includes("(")) {
//             const locationMatch = vehicleObj.location.match(/^(.+?)\s*\((.+?)\)$/);
//             City = locationMatch ? locationMatch[1].trim() : null;
//             State = locationMatch ? locationMatch[2].trim() : null;
//           } else if (vehicleObj.location.includes("-")) {
//             const [statePart, ...cityParts] = vehicleObj.location.split("-").map(part => part.trim());
//             State = statePart || null;
//             City = cityParts.join(" ") || null;
//           }

//           // Clean city name
//           const directionKeywords = ["NORTH", "EAST", "WEST", "SOUTH"];
//           const cleanedCity = City?.toUpperCase()
//             .split(" ")
//             .filter(word => !directionKeywords.includes(word.toUpperCase()))
//             .join(" ")
//             .trim();

//           // User lookup (same as bulk API)
//           let userId;
//           let markup = 0;
//           console.log("req query is ", req.query);
          
//           if (req.query.id) {
//             const user = await model.User.findById(req.query.id);
//             if (!user) throw new Error("User not found");
            
//             if (user.role === "admin" || user.role === "superadmin") {
//               userId = user._id.toString();
             
//               console.log("Admin user found:", userId);
//             } else if (user.role === "user") {
//               userId = user.AdminId?.toString();
//               markup = user.markup || 0;
//               if (!userId) throw new Error("AdminId not found for user");
//             }
//           } else {
//             const superAdmin = await model.User.findOne({ role: "superadmin" });
//             userId = superAdmin?._id.toString();
//             console.log("Using superadmin userId:", userId,cleanedCity);
//           }

//           // Location and pricing lookup
//           if (cleanedCity && userId) {
//             const locationData = await model.location.findOne({
//               City: cleanedCity,
//               userId,
//             });
//             console.log("location data  are ", locationData,userId);
            

//             if (locationData) {
//               const locationPricing = await model.LocationPricing.findOne({
//                 userId,
//                 locationId: locationData._id,
//               });

//               // Apply all location and pricing fields
//               vehicleObj.City = locationData.City || cleanedCity;
//               vehicleObj.State = locationData.State || State;
//               vehicleObj.Port1 = locationData.Port1 || null;
//               vehicleObj.Port2 = locationData.Port2 || null;
//               vehicleObj.markup = markup;

//               if (locationPricing) {
//                 vehicleObj.Price1 = locationPricing.Price1 || null;
//                 vehicleObj.Price2 = locationPricing.Price2 || null;
//                 vehicleObj.Price3 = locationPricing.Price3 || null;
//               }
//             } else {
//               console.log("No location data found for:", cleanedCity, userId);
//               vehicleObj.City = cleanedCity;
//               vehicleObj.State = State;
//               vehicleObj.markup = markup;
//             }
//           }

//           // Ensure critical fields exist
//           vehicleObj.markup = vehicleObj.markup || 0;
//           vehicleObj.current_bid = vehicleObj.current_bid || 0;
//           vehicleObj.Port1 = vehicleObj.Port1 || null;
//           vehicleObj.Port2 = vehicleObj.Port2 || null;
//           vehicleObj.Price1 = vehicleObj.Price1 || null;
//           vehicleObj.Price2 = vehicleObj.Price2 || null;
//           vehicleObj.Price3 = vehicleObj.Price3 || null;

//           return vehicleObj;
//         })
//       );

//       const processedData = {
//         data: processedVehicles,
//         // Include additional metadata if needed
//         count: processedVehicles.length,
//         success: true
//       };

//       const cacheSetSuccess = vinApiCache.set(cacheKey, processedData);
      
//       console.log("VIN Cache set:", {
//         cacheKey,
//         success: cacheSetSuccess,
//         dataLength: processedData.data.length,
//       });

//       res.json({
//         source: "api",
//         data: processedData,
//       });
//     } catch (error) {
//       console.error("VIN API Error:", {
//         message: error.message,
//         status: error.response?.status,
//         cacheKey,
//         stack: error.stack
//       });

//       if (error.response?.status === 404) {
//         // Cache not found responses too
//         vinApiCache.set(cacheKey, { data: [], error: "Vehicle not found" }, 60 * 5);
//         return res.status(404).json({
//           error: "Vehicle not found",
//           details: `No vehicle found with VIN/lot: ${params.lot}`
//         });
//       }

//       res.status(500).json({
//         error: "Failed to fetch car by VIN/lot",
//         details: error.message,
//       });
//     }
//   }
// }

// const getCarByVin = async (req, res) => {
//   try {
//     const { lot } = req.params;
//     console.log("Received VIN/lot request:", { lot });

//     const apiKey = "1f14a9d6-14e2-49b6-bc12-fd881b5a3e08";
//     if (!apiKey) {
//       return res.status(400).json({ error: "API key is required" });
//     }

//     // Validate VIN/lot format
//     if (!lot || !/^[a-zA-Z0-9]{4,17}$/.test(lot)) {
//       return res.status(400).json({ error: "Invalid VIN/lot format" });
//     }

//     const params = {
//       lot,
//       // Include any additional parameters needed for caching
//       id: req.query.id // Include user ID in cache key if present
//     };

//     const cacheKey = generateVinCacheKey(params);
//     const cachedData = vinApiCache.get(cacheKey);
//     console.log("VIN Cache check:", {
//       cacheKey,
//       cachedData: cachedData ? "found" : "not found",
//     });

//     if (cachedData) {
//       console.log("Serving VIN from cache");
//       return res.json({
//         source: "cache",
//         data: cachedData,
//       });
//     }

//     console.log(`VIN Request queued (${vinRequestQueue.length + 1} in queue)`);
//     vinRequestQueue.push({ req, res, params, apiKey, cacheKey });
//   } catch (error) {
//     console.error("VIN Route Error:", { 
//       message: error.message, 
//       stack: error.stack,
//       lot: req.params.lot 
//     });
//     res.status(500).json({
//       error: "Failed to fetch car by VIN/lot",
//       details: error.message,
//     });
//   }
// };

module.exports = { saveVehicles,getVehicles,getCars,getCarByVin };
