const XLSX = require('xlsx');
const path = require('path');
const fs = require('fs');
const csvParser = require('csv-parser');
const model = require('../Model/index')
const mongoose = require("mongoose")



// exports.uploadExcel = async (req, res) => {
//     const userId = req.user.id; 

//     if (!req.file) {
//         return res.status(400).json({ success: false, message: 'No file uploaded' });
//     }

//     const filePath = path.join(__dirname, '..', 'public', 'uploads', req.file.filename);
//     const ext = path.extname(filePath).toLowerCase();

//     try {
//         let data = [];

//         // Read the file based on its extension
//         if (ext === '.xlsx' || ext === '.xls') {
//             const workbook = XLSX.readFile(filePath);
//             const sheetName = workbook.SheetNames[0];
//             const sheet = workbook.Sheets[sheetName];
//             data = XLSX.utils.sheet_to_json(sheet, { raw: true });
//         } else if (ext === '.csv') {
//             const rows = [];
//             await new Promise((resolve, reject) => {
//                 fs.createReadStream(filePath)
//                     .pipe(csvParser())
//                     .on('data', (row) => {
//                         rows.push(row);
//                     })
//                     .on('end', () => resolve(rows))
//                     .on('error', (error) => reject(error));
//             });
//             data = rows;
//         } else {
//             return res.status(400).json({ success: false, message: 'Unsupported file format' });
//         }

//         // Check if data is empty
//         if (data.length === 0) {
//             return res.status(400).json({ success: false, message: 'Empty file' });
//         }

//         const extractedLocations = [];
//         const extractedPricing = [];

//         for (const row of data) {
//             const state = row.State ? row.State.toUpperCase() : null;
//             const city = row.City ? row.City.toUpperCase() : null;

//             if (!state || !city) continue; // Skip invalid rows

//             // Check if the location already exists
//             let location = await model.location.findOne({ State: state, City: city });

//             // If not, insert the new location
//             if (!location) {
//                 location = await model.location.create({ State: state, City: city });
//             }

//             // Prepare pricing data
//             extractedPricing.push({
//                 locationId: location._id, // Foreign key reference
//                 Price1: row.Aqaba,
//                 Price2: row.Jebel_Ali,
//                 Price3: row.Umm_Qasr,
//                 userId: userId,
//             });
//         }

//         // Insert pricing data in bulk
//         if (extractedPricing.length > 0) {
//             await model.LocationPricing.insertMany(extractedPricing);
//         }

//         return res.status(200).json({
//             success: true,
//             message: 'File processed successfully',
//             locationsInserted: extractedLocations,
//             pricingInserted: extractedPricing,
//         });

//     } catch (error) {
//         console.error('File processing error:', error);
//         return res.status(500).json({ success: false, message: 'Error processing file' });
//     }
// };

// exports.uploadExcel = async (req, res) => {
//     const userId = req.user.id;

//     if (!req.file) {
//         return res.status(400).json({ success: false, message: 'No file uploaded' });
//     }

//     const filePath = path.join(__dirname, '..', 'public', 'uploads', req.file.filename);
//     const ext = path.extname(filePath).toLowerCase();

//     try {
//         let data = [];

//         if (ext === '.xlsx' || ext === '.xls') {
//             const workbook = XLSX.readFile(filePath);
//             const sheetName = workbook.SheetNames[0];
//             const sheet = workbook.Sheets[sheetName];
//             data = XLSX.utils.sheet_to_json(sheet, { raw: true });
//         } else if (ext === '.csv') {
//             data = await new Promise((resolve, reject) => {
//                 const rows = [];
//                 fs.createReadStream(filePath, { highWaterMark: 64 * 1024 })
//                     .pipe(csvParser())
//                     .on('data', (row) => rows.push(row))
//                     .on('end', () => resolve(rows))
//                     .on('error', (error) => reject(error));
//             });
//         } else {
//             return res.status(400).json({ success: false, message: 'Unsupported file format' });
//         }

//         if (data.length === 0) {
//             return res.status(400).json({ success: false, message: 'Empty file' });
//         }

//         // Normalize and extract unique locations
//         const uniqueLocations = [...new Set(data.map(row => {
//             const state = row.State?.toString().trim().toUpperCase();
//             const city = row.City?.toString().trim().toUpperCase();
//             return state && city ? `${state}-${city}` : null;
//         }).filter(Boolean))];

//         const [states, cities] = uniqueLocations
//             .map(loc => loc.split('-'))
//             .reduce(([s, c], [state, city]) => [[...s, state], [...c, city]], [[], []]);

//         // Fetch all existing locations for this user
//         const existingLocations = await model.location.find({
//             State: { $in: states },
//             City: { $in: cities },
//             userId: userId
//         }).lean();

//         const existingLocationSet = new Set(existingLocations.map(loc => `${loc.State}-${loc.City}`));
//         const newLocations = uniqueLocations
//             .filter(loc => !existingLocationSet.has(loc))
//             .map(loc => {
//                 const [state, city] = loc.split('-');
//                 return { State: state, City: city, userId: userId };
//             });

//         let insertedLocations = [];
//         if (newLocations.length > 0) {
//             insertedLocations = await model.location.insertMany(newLocations, { ordered: false });
//         }

//         // Combine and map all locations
//         const allLocations = [...existingLocations, ...insertedLocations];
//         const locationMap = new Map(allLocations.map(loc => [`${loc.State}-${loc.City}`, loc._id]));

//         // Process pricing entries
//         const pricingEntries = [];
//         for (const row of data) {
//             const state = row.State?.toString().trim().toUpperCase();
//             const city = row.City?.toString().trim().toUpperCase();
//             if (!state || !city) continue;

//             const locationId = locationMap.get(`${state}-${city}`);
//             if (!locationId) continue;

//             const pricingEntry = {
//                 locationId: locationId,
//                 userId: userId,
//                 Price1: row.Aqaba ?? null,
//                 Price2: row.Jebel_Ali ?? null,
//                 Price3: row.Umm_Qasr ?? null
//             };

//             // Check for existing pricing entry with exact match
//             const existingPricing = await model.LocationPricing.findOne({
//                 locationId: pricingEntry.locationId,
//                 userId: pricingEntry.userId,
//                 Price1: pricingEntry.Price1,
//                 Price2: pricingEntry.Price2,
//                 Price3: pricingEntry.Price3
//             }).lean();

//             if (!existingPricing) {
//                 pricingEntries.push(pricingEntry);
//             }
//         }

//         let insertedPricing = [];
//         if (pricingEntries.length > 0) {
//             insertedPricing = await model.LocationPricing.insertMany(pricingEntries, { ordered: false });
//         }

//         // Clean up uploaded file
//         fs.unlink(filePath, (err) => {
//             if (err) console.error('Error deleting file:', err);
//         });

//         return res.status(200).json({
//             success: true,
//             message: 'File processed successfully',
//             locationsInserted: insertedLocations.length,
//             pricingInserted: insertedPricing.length
//         });

//     } catch (error) {
//         console.error('File processing error:', error);
//         return res.status(500).json({ success: false, message: 'Error processing file' });
//     }
// };


// exports.uploadExcel = async (req, res) => {
//     const userId = req.user.id;

//     if (!req.file) {
//         return res.status(400).json({ success: false, message: 'No file uploaded' });
//     }

//     const filePath = path.join(__dirname, '..', 'public', 'uploads', req.file.filename);
//     const ext = path.extname(filePath).toLowerCase();

//     try {
//         let data = [];

//         // Parse file based on extension
//         if (ext === '.xlsx' || ext === '.xls') {
//             const workbook = XLSX.readFile(filePath);
//             const sheetName = workbook.SheetNames[0];
//             const sheet = workbook.Sheets[sheetName];
//             data = XLSX.utils.sheet_to_json(sheet, { raw: true });
//         } else if (ext === '.csv') {
//             data = await new Promise((resolve, reject) => {
//                 const rows = [];
//                 fs.createReadStream(filePath, { highWaterMark: 64 * 1024 })
//                     .pipe(csvParser())
//                     .on('data', (row) => rows.push(row))
//                     .on('end', () => resolve(rows))
//                     .on('error', (error) => reject(error));
//             });
//         } else {
//             return res.status(400).json({ success: false, message: 'Unsupported file format' });
//         }

//         if (data.length === 0) {
//             return res.status(400).json({ success: false, message: 'Empty file' });
//         }

//         // Normalize and extract unique locations from the file
//         const fileLocations = data.map(row => {
//             const state = row.State?.toString().trim().toUpperCase();
//             const city = row.City?.toString().trim().toUpperCase();
//             return state && city ? { State: state, City: city } : null;
//         }).filter(Boolean);

//         const uniqueFileLocationKeys = [...new Set(fileLocations.map(loc => `${loc.State}-${loc.City}`))];
//         const [states, cities] = uniqueFileLocationKeys
//             .map(key => key.split('-'))
//             .reduce(([s, c], [state, city]) => [[...s, state], [...c, city]], [[], []]);

//         // Fetch all existing locations for this user
//         const existingLocations = await model.location.find({
//             State: { $in: states },
//             City: { $in: cities },
//             userId: userId
//         }).lean();

//         const existingLocationMap = new Map(existingLocations.map(loc => [`${loc.State}-${loc.City}`, loc._id]));
//         const updatedLocations = [];
//         const newLocations = [];

//         // Process locations: update existing, insert new
//         for (const loc of fileLocations) {
//             const key = `${loc.State}-${loc.City}`;
//             if (existingLocationMap.has(key)) {
//                 updatedLocations.push({
//                     updateOne: {
//                         filter: { _id: existingLocationMap.get(key), userId },
//                         update: { $set: { State: loc.State, City: loc.City } }
//                     }
//                 });
//             } else {
//                 newLocations.push({ State: loc.State, City: loc.City, userId });
//             }
//         }

//         let insertedLocations = [];
//         if (newLocations.length > 0) {
//             insertedLocations = await model.location.insertMany(newLocations, { ordered: false });
//             insertedLocations.forEach(loc => existingLocationMap.set(`${loc.State}-${loc.City}`, loc._id));
//         }

//         if (updatedLocations.length > 0) {
//             await model.location.bulkWrite(updatedLocations);
//         }

//         // Process pricing entries for all locations (existing and new)
//         const pricingOperations = [];
//         for (const row of data) {
//             const state = row.State?.toString().trim().toUpperCase();
//             const city = row.City?.toString().trim().toUpperCase();
//             if (!state || !city) continue;

//             const locationId = existingLocationMap.get(`${state}-${city}`);
//             if (!locationId) continue; // Shouldn't happen after insertion, but safety check

//             const pricingEntry = {
//                 locationId: locationId,
//                 userId: userId,
//                 Price1: row.Aqaba ?? null,
//                 Price2: row.Jebel_Ali ?? null,
//                 Price3: row.Umm_Qasr ?? null
//             };

//             // Update or insert pricing
//             pricingOperations.push({
//                 updateOne: {
//                     filter: {
//                         locationId: pricingEntry.locationId,
//                         userId: pricingEntry.userId
//                     },
//                     update: {
//                         $set: pricingEntry
//                     },
//                     upsert: true // Insert if no existing pricing entry
//                 }
//             });
//         }

//         let pricingResult = { matchedCount: 0, modifiedCount: 0, upsertedCount: 0 };
//         if (pricingOperations.length > 0) {
//             pricingResult = await model.LocationPricing.bulkWrite(pricingOperations);
//         }

//         // Clean up file asynchronously (no await)
//         fs.unlink(filePath, (err) => {
//             if (err) console.error('Error deleting file:', err);
//         });

//         return res.status(200).json({
//             success: true,
//             message: 'File processed successfully',
//             locationsInserted: insertedLocations.length,
//             locationsUpdated: updatedLocations.length,
//             pricingUpdated: pricingResult.modifiedCount,
//             pricingInserted: pricingResult.upsertedCount
//         });

//     } catch (error) {
//         console.error('File processing error:', error);
//         return res.status(500).json({ success: false, message: 'Error processing file' });
//     }
// };

// exports.uploadExcel = async (req, res) => {
//     const userId = req.user.id;

//     if (!req.file) {
//         return res.status(400).json({ success: false, message: 'No file uploaded' });
//     }

//     const filePath = path.join(__dirname, '..', 'public', 'uploads', req.file.filename);
//     const ext = path.extname(filePath).toLowerCase();

//     try {
//         let data = [];
//         if (ext === '.xlsx' || ext === '.xls') {
//             const workbook = XLSX.readFile(filePath);
//             const sheetName = workbook.SheetNames[0];
//             const sheet = workbook.Sheets[sheetName];
//             data = XLSX.utils.sheet_to_json(sheet, { raw: true });
//         } else if (ext === '.csv') {
//             data = await new Promise((resolve, reject) => {
//                 const rows = [];
//                 fs.createReadStream(filePath)
//                     .pipe(csvParser())
//                     .on('data', (row) => rows.push(row))
//                     .on('end', () => resolve(rows))
//                     .on('error', (error) => reject(error));
//             });
//         } else {
//             return res.status(400).json({ success: false, message: 'Unsupported file format' });
//         }

//         if (data.length === 0) {
//             return res.status(400).json({ success: false, message: 'Empty file' });
//         }

//         // Process each row
//         for (const row of data) {
//             const state = row.State?.toString().trim().toUpperCase();
//             const city = row.City?.toString().trim().toUpperCase();
            
//             if (!state || !city) continue;

//             // Check if location exists, if not create new
//             let location = await model.location.findOne({
//                 State: state,
//                 City: city,
//                 userId: userId
//             });

//             if (!location) {
//                 location = await model.location.create({
//                     State: state,
//                     City: city,
//                     userId: userId
//                 });
//             }

//             // Check if pricing exists, update or create
//             await model.LocationPricing.updateOne(
//                 {
//                     locationId: location._id,
//                     userId: userId
//                 },
//                 {
//                     $set: {
//                         Price1: row.Aqaba ?? null,
//                         Price2: row.Jebel_Ali ?? null,
//                         Price3: row.Umm_Qasr ?? null
//                     }
//                 },
//                 { upsert: true }
//             );
//         }

//         // Clean up file
//         fs.unlink(filePath, (err) => {
//             if (err) console.error('Error deleting file:', err);
//         });

//         return res.status(200).json({
//             success: true,
//             message: 'File processed successfully'
//         });

//     } catch (error) {
//         console.error('File processing error:', error);
//         return res.status(500).json({ success: false, message: 'Error processing file' });
//     }
// };
// exports.uploadExcel = async (req, res) => {
//     const userId = req.user.id;

//     if (!req.file) {
//         return res.status(400).json({ success: false, message: 'No file uploaded' });
//     }

//     const filePath = path.join(__dirname, '..', 'public', 'uploads', req.file.filename);
//     const ext = path.extname(filePath).toLowerCase();

//     try {
//         let data = [];
//         if (ext === '.xlsx' || ext === '.xls') {
//             const workbook = XLSX.readFile(filePath);
//             const sheetName = workbook.SheetNames[0];
//             const sheet = workbook.Sheets[sheetName];
//             data = XLSX.utils.sheet_to_json(sheet, { raw: true });
//         } else if (ext === '.csv') {
//             data = await new Promise((resolve, reject) => {
//                 const rows = [];
//                 fs.createReadStream(filePath)
//                     .pipe(csvParser())
//                     .on('data', (row) => rows.push(row))
//                     .on('end', () => resolve(rows))
//                     .on('error', (error) => reject(error));
//             });
//         } else {
//             return res.status(400).json({ success: false, message: 'Unsupported file format' });
//         }

//         if (data.length === 0) {
//             return res.status(400).json({ success: false, message: 'Empty file' });
//         }

//         // Process data in memory
//         const locationsMap = new Map();
//         const pricingOperations = [];

//         // Normalize and prepare data
//         for (const row of data) {
//             const state = row.State?.toString().trim().toUpperCase();
//             const city = row.City?.toString().trim().toUpperCase();
            
//             if (!state || !city) continue;

//             const locationKey = `${state}-${city}`;
//             locationsMap.set(locationKey, { State: state, City: city, userId });

//             pricingOperations.push({
//                 state,
//                 city,
//                 Price1: row.Aqaba ?? null,
//                 Price2: row.Jebel_Ali ?? null,
//                 Price3: row.Umm_Qasr ?? null
//             });
//         }

//         // Fetch all existing locations in one query
//         const locationKeys = Array.from(locationsMap.keys());
//         const existingLocations = await model.location.find({
//             userId: userId,
//             $or: locationKeys.map(key => {
//                 const [State, City] = key.split('-');
//                 return { State, City };
//             })
//         }).lean();

//         // Build a map of existing locations
//         const existingLocationMap = new Map(
//             existingLocations.map(loc => [`${loc.State}-${loc.City}`, loc._id])
//         );

//         // Insert only new locations
//         const newLocations = [];
//         for (const [key, location] of locationsMap) {
//             if (!existingLocationMap.has(key)) {
//                 newLocations.push(location);
//             }
//         }

//         let insertedCount = 0;
//         if (newLocations.length > 0) {
//             const insertedLocations = await model.location.insertMany(newLocations, { ordered: false });
//             insertedCount = insertedLocations.length;
//             insertedLocations.forEach(loc => {
//                 existingLocationMap.set(`${loc.State}-${loc.City}`, loc._id);
//             });
//         }

//         // Prepare pricing updates (update only, no duplicates)
//         const finalPricingOperations = pricingOperations.map(op => {
//             const locationKey = `${op.state}-${op.city}`;
//             const locationId = existingLocationMap.get(locationKey);

//             return {
//                 updateOne: {
//                     filter: {
//                         locationId: locationId,
//                         userId: userId
//                     },
//                     update: {
//                         $set: {
//                             Price1: op.Price1,
//                             Price2: op.Price2,
//                             Price3: op.Price3
//                         }
//                     },
//                     upsert: true // Only upserts if no match, but filter ensures uniqueness
//                 }
//             };
//         });

//         // Execute pricing updates
//         let pricingResult = { modifiedCount: 0, upsertedCount: 0 };
//         if (finalPricingOperations.length > 0) {
//             pricingResult = await model.LocationPricing.bulkWrite(finalPricingOperations);
//         }

//         // Clean up file
//         fs.unlink(filePath, (err) => {
//             if (err) console.error('Error deleting file:', err);
//         });

//         return res.status(200).json({
//             success: true,
//             message: 'File processed successfully',
//             locationsInserted: insertedCount,
//             pricingUpdated: pricingResult.modifiedCount,
//             pricingInserted: pricingResult.upsertedCount
//         });

//     } catch (error) {
//         console.error('File processing error:', error);
//         return res.status(500).json({ success: false, message: 'Error processing file' });
//     }
// };




exports.uploadExcel = async (req, res) => {
    const userId = req.user.id;

    if (!req.file) {
        return res.status(400).json({ success: false, message: 'No file uploaded' });
    }

    const filePath = path.join(__dirname, '..', 'public', 'Uploads', req.file.filename);
    const ext = path.extname(filePath).toLowerCase();

    try {
        // Step 1: Parse the uploaded file
        let data = [];
        if (ext === '.xlsx' || ext === '.xls') {
            const workbook = XLSX.readFile(filePath);
            const sheetName = workbook.SheetNames[0];
            const sheet = workbook.Sheets[sheetName];
            data = XLSX.utils.sheet_to_json(sheet, { raw: true });
        } else if (ext === '.csv') {
            data = await new Promise((resolve, reject) => {
                const rows = [];
                fs.createReadStream(filePath)
                    .pipe(csvParser())
                    .on('data', (row) => {
                        // Skip empty rows
                        if (Object.values(row).every(val => val === '' || val === null || val === undefined)) {
                            return;
                        }
                        rows.push(row);
                    })
                    .on('end', () => {
                        console.log('Parsed CSV rows:', rows); // Debug log
                        resolve(rows);
                    })
                    .on('error', (error) => reject(error));
            });
        } else {
            return res.status(400).json({ success: false, message: 'Unsupported file format' });
        }

        if (data.length === 0) {
            return res.status(400).json({ success: false, message: 'Empty file' });
        } 
        console.log("data is ", data);
    
        // Step 2: Delete existing LocationPricing records for this user
        const deleteResult = await model.LocationPricing.deleteMany({ userId });

        // Step 3: Process data in memory
        const locationsMap = new Map();
        const pricingMap = new Map();

        // Normalize and prepare data
        for (const row of data) {
            const state = row.State?.toString().trim().toUpperCase();
            const city = row.City?.toString().trim().toUpperCase();
            const port1 = row.Shipping_from_port_1?.toString().trim() || '';
            const port2 = row.Shipping_from_port_2?.toString().trim() || '';

            if (!state || !city) continue;

            const locationKey = `${state}-${city}`;
            locationsMap.set(locationKey, { State: state, City: city, Port1: port1, Port2: port2, userId });

            // Store the latest pricing data for this location
            pricingMap.set(locationKey, {
                state,
                city,
                Price1: row.Aqaba ?? null,
                Price2: row.Jebel_Ali ?? null,
                Price3: row.Umm_Qasr ?? null,
            });
        }

        // Step 4: Fetch existing locations for this user
        const locationKeys = Array.from(locationsMap.keys());
        const existingLocations = await model.location.find({
            userId,
            $or: locationKeys.map(key => {
                const [State, City] = key.split('-');
                return { State, City };
            })
        }).lean();

        // Build a map of existing locations
        const existingLocationMap = new Map(
            existingLocations.map(loc => [`${loc.State}-${loc.City}`, loc._id])
        );

        // Step 5: Insert new locations if they don't exist
        const newLocations = [];
        for (const [key, location] of locationsMap) {
            if (!existingLocationMap.has(key)) {
                newLocations.push(location);
            }
        }

        let insertedCount = 0;
        if (newLocations.length > 0) {
            const insertedLocations = await model.location.insertMany(newLocations, { ordered: false });
            insertedCount = insertedLocations.length;
            insertedLocations.forEach(loc => {
                existingLocationMap.set(`${loc.State}-${loc.City}`, loc._id);
            });
        }

        // Step 6: Prepare new LocationPricing records
        const pricingRecords = Array.from(pricingMap.values()).map(op => {
            const locationKey = `${op.state}-${op.city}`;
            const locationId = existingLocationMap.get(locationKey);

            return {
                locationId,
                userId,
                Price1: op.Price1,
                Price2: op.Price2,
                Price3: op.Price3,
            };
        });

        // Step 7: Insert new LocationPricing records
        let pricingInsertedCount = 0;
        if (pricingRecords.length > 0) {
            const insertedPricing = await model.LocationPricing.insertMany(pricingRecords, { ordered: false });
            pricingInsertedCount = insertedPricing.length;
        }

        // Step 8: Clean up file
        fs.unlink(filePath, (err) => {
            if (err) console.error('Error deleting file:', err);
        });

        // Step 9: Send response
        return res.status(200).json({
            success: true,
            message: 'File processed successfully',
            locationsInserted: insertedCount,
            pricingInserted: pricingInsertedCount,
            pricingDeleted: deleteResult.deletedCount
        });

    } catch (error) {
        console.error('File processing error:', error);
        return res.status(500).json({ success: false, message: 'Error processing file' });
    }
};

exports.getAdminPricing = async (req, res) => {
    try {
        const userId = req.user.id;

        // Fetch pricing details from LocationPricing table
        const pricingDetails = await model.LocationPricing.find({ userId }).lean();
          
        if (!pricingDetails.length) {
            return res.status(404).json({ message: "No records found" });
        }

        // Get all unique locationIds from pricingDetails
        const locationIds = pricingDetails.map(pricing => pricing.locationId);

        // Fetch city, state, port1, and port2 for these locationIds
        const locations = await model.location.find({ _id: { $in: locationIds } }).lean();
 
        // Create a map for quick lookup
        const locationMap = locations.reduce((acc, loc) => {
            acc[loc._id] = { 
                city: loc.City, 
                state: loc.State, 
                port1: loc.Port1 || "N/A", 
                port2: loc.Port2 || "N/A" 
            };
            return acc;
        }, {});

        // Format the response
        const formattedData = pricingDetails.map(pricing => ({
            _id: pricing._id,
            City: locationMap[pricing.locationId]?.city || "N/A",
            State: locationMap[pricing.locationId]?.state || "N/A",
            Price1: pricing.Price1,
            Price2: pricing.Price2,
            Price3: pricing.Price3,
            Port1: locationMap[pricing.locationId]?.port1 || "N/A",
            Port2: locationMap[pricing.locationId]?.port2 || "N/A",
            userId: pricing.userId
        }));

        return res.status(200).json({
            success: true,
            message: "Pricing details fetched successfully",
            data: formattedData
        });

    } catch (error) {
        console.error("Error fetching pricing details:", error);
        res.status(500).json({ message: "Internal server error" });
    }
};

  exports.updatePricing = async (req, res) => {
    console.log("data in body ", req.body);
    
    const { _id,  Price1, Price2, Price3 } = req.body; // Destructure the required fields from the request body

    try {
        // Find the document by ID
        const pricingDetail = await model.LocationPricing.findOne({ _id: _id });

        if (!pricingDetail) {
            return res.status(404).json({ message: 'Pricing detail not found' });
        }

        // Update the fields manually
      
        pricingDetail.Price1 = Price1;
        pricingDetail.Price2 = Price2;
        pricingDetail.Price3 = Price3;

        // Save the updated document
        const updatedPricing = await pricingDetail.save();

        res.status(200).json({
            message: 'Pricing detail updated successfully',
            data: updatedPricing,
        });
    } catch (error) {
        console.error('Error updating pricing detail:', error);
        res.status(500).json({ message: 'Internal server error' });
    }
};  

// exports.updatePricingData = async (req, res) => {
//     const productId  = req.body.id; // Get productId from URL params
//     const userId = req.user.id; // Get userId from authenticated user
//     const updatedData = req.body; // Get updated data from request body

//     try {
//         // Find the pricing document for the given userId and productId
//         const pricing = await model.LocationPricing.findOne({ userId, productId });

//         if (!pricing) {
//             return res.status(404).json({ message: 'Pricing data not found' });
//         }

//         // Update the pricing data
//         pricing.State = updatedData.State || pricing.State;
//         pricing.City = updatedData.City || pricing.City;
//         pricing.Price1 = updatedData.Price1 || pricing.Price1;
//         pricing.Price2 = updatedData.Price2 || pricing.Price2;
//         pricing.Price3 = updatedData.Price3 || pricing.Price3;

//         // Save the updated document
//         await pricing.save();

//         // Return success response
//         res.status(200).json({ message: 'Pricing data updated successfully', data: pricing });
//     } catch (error) {
//         console.error('Error updating pricing data:', error);
//         res.status(500).json({ message: 'Internal server error' });
//     }
// };
