
const { default: axios } = require('axios');
const model = require('../Model/index'); // Adjust the path to your Purchase model
const mongoose = require('mongoose');
const cloudinary = require('cloudinary').v2;
const stream = require('stream');



// Controller to create a new purchase

const createPurchase = async (req, res) => {
  try {
    console.log("req body is ", req.body);
    console.log("req user is ", req.user);

    let userId;
    let email;

    // 🧠 Check if userId is a JSON string or a normal ID string
    if (req.body.userId?.startsWith?.('{')) {
      try {
        const userObj = JSON.parse(req.body.userId);
        userId = userObj.userId;
        email = userObj.email;
      } catch (e) {
        return res.status(400).json({
          success: false,
          message: 'Invalid userId JSON string',
        });
      }
    } else {
      userId = req.body.userId || req.user?.id;
      email = req.user?.email || ""; // fallback if not provided
    }

    console.log("Parsed User ID:", userId);
    console.log("Parsed Email:", email);

    const {
      vin,
      lotPrice,
      auctionFees,
      portPrice,
      portName,
      lotNumber,
      photoUrl,
      lot_id,
      title,
      markup,
      subtotal
    } = req.body;

    if (!userId || !vin) {
      return res.status(400).json({
        success: false,
        message: 'Missing required fields: userId or vin',
      });
    }

    const existingPurchase = await model.Purchase.findOne({ Vin: vin });
    if (existingPurchase) {
      return res.status(400).json({
        success: false,
        message: 'A purchase with this VIN already exists',
      });
    }

    const newPurchase = new model.Purchase({
      userId,
      lotNumber: lot_id || "",
      vehicle_type: title || "",
      email,
      Vin: vin,
     
      bid: lotPrice || 0,
      auctionFees: auctionFees || 0,
      shippingPort: portName || "",
      photoUrl: photoUrl || [],
      shipping: {
        cost: portPrice || 0,
        paid: 0,
        arrival: null,
        total_cost:subtotal,
 Markup_shipping_cost:markup,
      },
      
      purchase_payment: {
        due: 0,
        paid: 0,
      },
    });

    const savedPurchase = await newPurchase.save();

    return res.status(201).json({
      success: true,
      message: 'Purchase created successfully',
      data: savedPurchase,
    });
  } catch (error) {
    console.error('Error creating purchase:', error);
    return res.status(500).json({
      success: false,
      message: 'Server error while creating purchase',
      error: error.message,
    });
  }
};





const getPurchasesByAdminId = async (req, res) => {
  try {
    console.log("req.user.role ", req.user.role);
    
    let purchases;
    // status  = pending , accepted , rejected ,all
  
    
    var statusFilter =  (req.body.status || 'all').toLowerCase() ;
   console.log("status passes ", statusFilter);
  
    // console.log();
    var filter = {
    };

    // Apply status filter if not "All"
    if (statusFilter !== 'all') {
      filter.status = statusFilter;
    }

    let userIdsToFilter = [];

    if (req.user.role == "user"){
      filter.userId = { $in: req.user.id};
    }
    else if (req.user.role == "admin"||req.user.role==="superadmin"){
 console.log("admin called");
 
      const targetUserId = req.body.id || "all";
      console.log("target list is ", targetUserId);
      
     if (targetUserId === 'all') {
  const users = await model.User.find({ AdminId: req.user.id }).select('_id');
  filter.userId = users.map((user) => user._id);
  console.log("FILTER USERID ", filter);
} else {
  userIdsToFilter = [targetUserId];
  filter.userId = { $in: userIdsToFilter }; // ✅ Only assign this if specific userId provided
}
 // works for both single and multiple userIds
    }
    else {
      return res.status(403).json({
        success: false,
        message: 'Unauthorized access',
      });
    }

//  // Validate adminId format
//         if (!mongoose.Types.ObjectId.isValid(adminId)) {
//           return res.status(400).json({
//             success: false,
//             message: 'Invalid admin ID format',
//           });
//         }

//         // Validate targetUserId format
//         if (!mongoose.Types.ObjectId.isValid(targetUserId)) {
//           return res.status(400).json({
//             success: false,
//             message: 'Invalid User ID format',
//           });
//         }
console.log("filter is ", filter);

        purchases = await model.Purchase.find(filter)
        .populate('userId', 'username email')
        .select('vehicle_type Vin lotNumber bid auctionFees shippingPort transportStatus photoUrl status shipping purchase_payment containerNumber createdAt');





      

    // Handle empty result
    if (!purchases || !purchases.length) {
      return res.status(404).json({
        success: false,
        message: 'No purchases found',
      });
    }
    console.log("purchases ", purchases);
    

    // Return result
    return res.status(200).json({
      success: true,
      message: 'Purchases retrieved successfully',
      data: purchases,
    });
  } catch (error) {
    console.error('Error fetching purchases by admin ID:', error);
    return res.status(500).json({
      success: false,
      message: 'Server error while fetching purchases',
      error: error.message,
    });
  }
};


const UpdatePurchase = async (req, res) => {
  try {


    console.log("req bidy ", req.body.status.status);
    const purchaseId = req.body.id;
    const status = req.body.status.status



    // Validate input
    if (!purchaseId || !['accepted', 'rejected'].includes(status)) {
      return res.status(400).json({
        success: false,
        message: 'Purchase ID and valid status (accepted/rejected) are required',
      });
    }

    // Update the status
    const updatedPurchase = await model.Purchase.findByIdAndUpdate(
      purchaseId,
      { status: status },
      { new: true }
    );

    if (!updatedPurchase) {
      return res.status(404).json({
        success: false,
        message: 'Purchase not found',
      });
    }

    return res.status(200).json({
      success: true,
      message: `Purchase has been ${status}`,
      data: updatedPurchase,
    });
  } catch (error) {
    console.error('Error updating purchase status:', error);
    return res.status(500).json({
      success: false,
      message: 'Server error while updating purchase status',
      error: error.message,
    });
  }
};




// Controller to fetch sales history from third-party API
const getSearchHistory = async (req, res) => {
  try {
    const { vin } = req.query;

    if (!vin) {
      return res.status(400).json({ message: 'VIN is required' });
    }

    // Call the third-party API
    const response = await axios.get(`https://api.apicar.store/api/cars/vin/all?vin=${vin}`, {
      headers: {
        'api-key': '1f14a9d6-14e2-49b6-bc12-fd881b5a3e08',
      },
    });
    console.log("respsoce of api serach history is ",response?.data[0]?.sale_history );
    

    const saleHistory = response?.data[0]?.sale_history || [];

    // Format the sales history data
    const formattedData = saleHistory.map((sale) => ({
      auction: sale.base_site || 'N/A',
      date: sale.updated_at ? new Date(sale.updated_at).toLocaleDateString() : 'N/A',
      lotNumber: sale.lot_id || 'N/A',
      finalBid: sale.purchase_price ? `$${sale.purchase_price}` : 'N/A',
      odometer: sale.odometer ? `${sale.odometer} mi` : 'N/A',
      status: sale.sale_status || 'N/A',
      seller: sale.seller || 'N/A',
    }));

    res.status(200).json({ success: true, data: formattedData });
  } catch (error) {
    console.error('Error fetching sales history:', error.message);
    res.status(500).json({ message: 'Failed to load sales history. Please try again later.' });
  }
};




const getCurrentBid = async (req, res) => {
  try {
    const { lot_id, site } = req.query;

    // Validate required query parameters
    if (!lot_id || !site) {
      return res.status(400).json({ message: 'Lot ID and site are required' });
    }

    // Validate site parameter
    if (!['1', '2'].includes(site)) {
      return res.status(400).json({ message: 'Invalid site value. Use 1 for Copart or 2 for IAAI' });
    }

    // Call the third-party API
    const response = await axios.get('https://api.apicar.store/api/cars/current-bid', {
      params: {
        lot_id,
        site
      },
      headers: {
        'api-key': '1f14a9d6-14e2-49b6-bc12-fd881b5a3e08',
      },
    });

    // Extract and format the current bid data
    const bidData = response?.data || {};
    const formattedData = {
      lotId: bidData.lot_id || 'N/A',
      site: bidData.site === '1' ? 'Copart' : bidData.site === '2' ? 'IAAI' : 'N/A',
      currentBid: bidData.current_bid ? `$${bidData.current_bid}` : 'N/A',
      bidStatus: bidData.bid_status || 'N/A',
      lastUpdated: bidData.updated_at ? new Date(bidData.updated_at).toLocaleDateString() : 'N/A',
    };

    res.status(200).json({ success: true, data: formattedData });
  } catch (error) {
    console.error('Error fetching current bid:', error.message);
    res.status(500).json({ message: 'Failed to load current bid. Please try again later.' });
  }
};




cloudinary.config({
    cloud_name: 'dlsnr7pei',
    api_key: '212231468523698',
    api_secret: 'sAO8z4bb08dELWI5nNYZ-_DMsw8',
    secure: true,
});
const uploadImages = async (req, res) => {
  const { id, containerNumber } = req.body;

  console.log("req body (containerNumber):", containerNumber);
  console.log("req file:", req.file);

  if (!id) {
    return res.status(400).json({ message: 'Submission failed: objectId is required.' });
  }

  if (!req.file && !containerNumber) {
    return res.status(400).json({ message: 'Submission failed: required fields are empty.' });
  }

  try {
    // 🔄 Find the existing MongoDB document by ID
    const existingPost = await model.Purchase.findById(id);

    if (!existingPost) {
      return res.status(404).json({ message: 'Post not found.' });
    }

    // 📷 Upload image to Cloudinary if file is provided
    if (req.file) {
      const options = {
        resource_type: 'auto',
        public_id: `uploads/${Date.now()}`,
        overwrite: true,
      };

      const bufferStream = new stream.PassThrough();
      bufferStream.end(req.file.buffer);

      const result = await new Promise((resolve, reject) => {
        bufferStream.pipe(
          cloudinary.uploader.upload_stream(options, (error, result) => {
            if (error) return reject(error);
            resolve(result);
          })
        );
      });

      // Push uploaded image URL to photoUrl array
      existingPost.photoUrl = existingPost.photoUrl || [];
      existingPost.photoUrl.push(result.secure_url);
    }

    // 🧾 Update container number if provided
    if (containerNumber) {
      existingPost.containerNumber = containerNumber;
    }

    // 💾 Save the updated document
    await existingPost.save();

    return res.status(200).json({
      status: true,
      message: 'Data processed and post updated successfully.',
      updatedPost: existingPost,
    });

  } catch (error) {
    console.error('Error:', error);
    return res.status(500).json({
      message: 'Upload or update failed.',
      error: error.message || error,
    });
  }
};


const UpdatePurchaseDetails = async (req, res) => {
  try {
    console.log("req body is ", req.body);

    const {
      id,
      shippingStatus,
      arrivalDate,
      'shipping.paid': shippingPaid,
      'purchase_payment.paid': purchasePaymentPaid,
      containerNumber,
    } = req.body;

    if (!id || !mongoose.Types.ObjectId.isValid(id)) {
      return res.status(400).json({
        success: false,
        message: 'Valid Purchase ID is required',
      });
    }

    const validShippingStatuses = ['dispatch', 'loaded', 'delivered'];
    const updates = {};

    if (shippingStatus && !validShippingStatuses.includes(shippingStatus)) {
      return res.status(400).json({
        success: false,
        message: 'Invalid shipping status. Must be one of: dispatch, loaded, delivered',
      });
    }
    if (arrivalDate && isNaN(Date.parse(arrivalDate))) {
      return res.status(400).json({
        success: false,
        message: 'Invalid arrival date format',
      });
    }

    // Fetch existing purchase record
    const purchase = await mongoose.model("Purchase").findById(id);
    if (!purchase) {
      return res.status(404).json({
        success: false,
        message: 'Purchase not found',
      });
    }

    // Handle shipping status
    if (shippingStatus) updates['shipping.status'] = shippingStatus;

    // Handle arrival date
    if (arrivalDate) updates['shipping.arrival'] = new Date(arrivalDate);

    // Add to existing shipping paid
    if (shippingPaid !== undefined) {
      if (typeof shippingPaid !== 'number' || shippingPaid < 0) {
        return res.status(400).json({
          success: false,
          message: 'Shipping paid amount must be a non-negative number',
        });
      }
      const currentShippingPaid = purchase.shipping?.paid || 0;
      updates['shipping.paid'] = currentShippingPaid + shippingPaid;
    }

    // Add to existing purchase payment paid
    if (purchasePaymentPaid !== undefined) {
      if (typeof purchasePaymentPaid !== 'number' || purchasePaymentPaid < 0) {
        return res.status(400).json({
          success: false,
          message: 'Purchase payment paid amount must be a non-negative number',
        });
      }
      const currentPurchasePaid = purchase.purchase_payment?.paid || 0;
      updates['purchase_payment.paid'] = currentPurchasePaid + purchasePaymentPaid;
    }

    // Handle container number
    if (containerNumber) updates.containerNumber = containerNumber;

    if (Object.keys(updates).length === 0) {
      return res.status(400).json({
        success: false,
        message: 'No valid fields provided to update',
      });
    }

    // Perform the update
    const updatedPurchase = await mongoose.model("Purchase").findByIdAndUpdate(
      id,
      { $set: updates },
      { new: true, runValidators: true }
    );

    return res.status(200).json({
      success: true,
      message: 'Purchase details updated successfully',
      data: updatedPurchase,
    });
  } catch (error) {
    console.error('Error updating purchase details:', error);
    return res.status(500).json({
      success: false,
      message: 'Server error while updating purchase details',
      error: error.message,
    });
  }
};



// const getProfitSummary = async (req, res) => {
//   try {
//     console.log("req.user.role ", req.user.role);
    
//     let filter = {};

//     // Role-based filtering
//     if (req.user.role === "admin") {
//       console.log("admin ");
      
//       const targetUserId = req.body.id || "all";
//       console.log("target list is ", targetUserId);
      
//       if (targetUserId === "all") {
//         const users = await model.User.find({ AdminId: req.user.id }).select('_id');
//         filter.userId = { $in: users.map((user) => user._id) };
//         console.log("FILTER USERID ", filter);
//       } 
//       else {
//         // Validate targetUserId format
//         if (!mongoose.Types.ObjectId.isValid(targetUserId)) {
//           return res.status(400).json({
//             success: false,
//             message: 'Invalid User ID format',
//           });
//         }
//         filter.userId = { $in: [targetUserId] };
//       }
//     } else {
//       return res.status(403).json({
//         success: false,
//         message: 'Unauthorized access',
//       });
//     }

//     console.log("filter is ", filter);

//     // Aggregate query to calculate sums and count
//     const totals = await model.Purchase.aggregate([
//       { $match: filter }, // Match based on userId
//       {
//         $group: {
//           _id: "$userId", // Group by userId field from Purchase model
//           purchaseTotal: { $sum: { $add: ["$purchase_payment.due", "$purchase_payment.paid"] } },
//           shippingTotal: { $sum: "$shipping.cost" },
//           totalPaid: { $sum: { $add: ["$shipping.paid", "$purchase_payment.paid"] } },
//           purchaseCount: { $sum: 1 }, // Count the number of purchases (cars) per user
//         }
//       },
//       {
//         $lookup: {
//           from: 'users',
//           localField: '_id', // _id from $group is userId
//           foreignField: '_id', // Match with _id in users collection
//           as: 'user'
//         }
//       },
//       { $unwind: '$user' },
//       {
//         $project: {
//           _id: 0,
//           userId: '$_id',
//           username: '$user.username',
//           email: '$user.email',
//           purchaseTotal: 1,
//           shippingTotal: 1,
//           totalPaid: 1,
//           purchaseCount: 1, // Include the count of purchases
//           shippingProfit: { $literal: 0 },
//           purchaseProfit: { $literal: 0 },
//           totalProfit: { $literal: 0 }
//         }
//       }
//     ]);

//     // Handle empty result
//     if (!totals || !totals.length) {
//       return res.status(404).json({
//         success: false,
//         message: 'No purchase totals found',
//       });
//     }

//     console.log("totals ", totals);

//     // Return result
//     return res.status(200).json({
//       success: true,
//       message: 'Purchase totals retrieved successfully',
//       data: totals,
//     });
//   } catch (error) {
//     console.error('Error fetching purchase totals by admin ID:', error);
//     return res.status(500).json({
//       success: false,
//       message: 'Server error while fetching purchase totals',
//       error: error.message,
//     });
//   }
// };




// const getProfitSummary = async (req, res) => {
//   try {
//     console.log("req.user.role ", req.user.role);
    
//     let filter = {};

//     // Role-based filtering
//     if (req.user.role === "admin") {
//       console.log("admin ");
      
//       const targetUserId = req.body.id || "all";
//       console.log("target list is ", targetUserId);
      
//       if (targetUserId === "all") {
//         const users = await model.User.find({ AdminId: req.user.id }).select('_id');
//         filter.userId = { $in: users.map((user) => user._id) };
//         console.log("FILTER USERID ", filter);
//       } 
//       else {
//         // Validate targetUserId format
//         if (!mongoose.Types.ObjectId.isValid(targetUserId)) {
//           return res.status(400).json({
//             success: false,
//             message: 'Invalid User ID format',
//           });
//         }
//         filter.userId = { $in: [targetUserId] };
//       }
//     } else {
//       return res.status(403).json({
//         success: false,
//         message: 'Unauthorized access',
//       });
//     }

//     console.log("filter is ", filter);

//     // Fetch raw purchase data for logging individual details
//     const rawPurchases = await model.Purchase.find(filter).populate('userId', 'username email');
//     console.log('Raw Purchase Data for Manual Verification:');
//     let manualTotals = {};
//     rawPurchases.forEach((purchase, index) => {
//       const userId = purchase.userId?._id.toString() || 'undefined';
//       console.log(`Purchase ${index + 1} for User ${purchase.userId?.username || 'undefined'} (ID: ${userId}):`);
//       console.log(`  purchase_payment.due: ${purchase.purchase_payment.due} (type: ${typeof purchase.purchase_payment.due})`);
//       console.log(`  purchase_payment.paid: ${purchase.purchase_payment.paid} (type: ${typeof purchase.purchase_payment.paid})`);
//       console.log(`  purchase_payment.base_purchase_cost: ${purchase.purchase_payment.base_purchase_cost} (type: ${typeof purchase.purchase_payment.base_purchase_cost})`);
//       console.log(`  shipping.cost: ${purchase.shipping.cost} (type: ${typeof purchase.shipping.cost})`);
//       console.log(`  shipping.Markup_shipping_cost: ${purchase.shipping.Markup_shipping_cost} (type: ${typeof purchase.shipping.Markup_shipping_cost})`);
//       console.log(`  shipping.paid: ${purchase.shipping.paid} (type: ${typeof purchase.shipping.paid})`);
//       console.log(`  Calculated purchase_total (due + paid): ${purchase.purchase_payment.due + purchase.purchase_payment.paid}`);
//       console.log(`  Calculated shipping_total (cost + Markup_shipping_cost): ${purchase.shipping.cost + purchase.shipping.Markup_shipping_cost}`);
//       console.log(`  Calculated total_paid (purchase_payment.paid + shipping.paid): ${purchase.purchase_payment.paid + purchase.shipping.paid}`);
//       console.log(`  Calculated purchase_profit (|purchase_total - base_purchase_cost|): ${Math.abs((purchase.purchase_payment.due + purchase.purchase_payment.paid) - purchase.purchase_payment.base_purchase_cost)}`);
//       console.log(`  Calculated shipping_profit (|shipping.cost - Markup_shipping_cost|): ${Math.abs(purchase.shipping.cost - purchase.shipping.Markup_shipping_cost)}`);
//       console.log(`  Calculated total_profit (purchase_profit + shipping_profit): ${Math.abs((purchase.purchase_payment.due + purchase.purchase_payment.paid) - purchase.purchase_payment.base_purchase_cost) + Math.abs(purchase.shipping.cost - purchase.shipping.Markup_shipping_cost)}`);

//       // Accumulate manual totals for cross-checking
//       if (!manualTotals[userId]) {
//         manualTotals[userId] = {
//           purchaseTotal: 0,
//           shippingTotal: 0,
//           totalPaid: 0,
//           purchaseCount: 0,
//           basePurchaseCost: 0,
//           shippingCost: 0,
//           markupShippingCost: 0,
//           purchaseProfit: 0,
//           shippingProfit: 0,
//         };
//       }
//       manualTotals[userId].purchaseTotal += (purchase.purchase_payment.due + purchase.purchase_payment.paid);
//       manualTotals[userId].shippingTotal += (purchase.shipping.cost + purchase.shipping.Markup_shipping_cost);
//       manualTotals[userId].totalPaid += (purchase.purchase_payment.paid + purchase.shipping.paid);
//       manualTotals[userId].basePurchaseCost += purchase.purchase_payment.base_purchase_cost;
//       manualTotals[userId].shippingCost += purchase.shipping.cost;
//       manualTotals[userId].markupShippingCost += purchase.shipping.Markup_shipping_cost;
//       manualTotals[userId].purchaseCount += 1;
//       manualTotals[userId].purchaseProfit += Math.abs((purchase.purchase_payment.due + purchase.purchase_payment.paid) - purchase.purchase_payment.base_purchase_cost);
//       manualTotals[userId].shippingProfit += Math.abs(purchase.shipping.cost - purchase.shipping.Markup_shipping_cost);
//     });

//     // Log manual totals for verification
//     console.log('Manual Totals for Cross-Checking:');
//     Object.keys(manualTotals).forEach((userId) => {
//       const totals = manualTotals[userId];
//       console.log(`User ID: ${userId}`);
//       console.log(`  Manual purchaseTotal: ${totals.purchaseTotal}`);
//       console.log(`  Manual shippingTotal: ${totals.shippingTotal}`);
//       console.log(`  Manual totalPaid: ${totals.totalPaid}`);
//       console.log(`  Manual purchaseCount: ${totals.purchaseCount}`);
//       console.log(`  Manual purchaseProfit: ${totals.purchaseProfit}`);
//       console.log(`  Manual shippingProfit: ${totals.shippingProfit}`);
//       console.log(`  Manual totalProfit: ${totals.purchaseProfit + totals.shippingProfit}`);
//     });

//     // Aggregate query to calculate sums and count
//     const totals = await model.Purchase.aggregate([
//       { $match: filter }, // Match based on userId
//       {
//         $group: {
//           _id: "$userId", // Group by userId field from Purchase model
//           // Formula: purchase_total = purchase_payment.due + purchase_payment.paid
//           purchaseTotal: { 
//             $sum: { 
//               $add: [
//                 { $toDouble: { $ifNull: ["$purchase_payment.due", 0] } }, 
//                 { $toDouble: { $ifNull: ["$purchase_payment.paid", 0] } }
//               ] 
//             } 
//           },
//           // Formula: shipping_total = shipping.cost + shipping.Markup_shipping_cost
//           shippingTotal: { 
//             $sum: { 
//               $add: [
//                 { $toDouble: { $ifNull: ["$shipping.cost", 0] } }, 
//                 { $toDouble: { $ifNull: ["$shipping.Markup_shipping_cost", 0] } }
//               ] 
//             } 
//           },
//           // Formula: total_paid = purchase_payment.paid + shipping.paid
//           totalPaid: { 
//             $sum: { 
//               $add: [
//                 { $toDouble: { $ifNull: ["$purchase_payment.paid", 0] } }, 
//                 { $toDouble: { $ifNull: ["$shipping.paid", 0] } }
//               ] 
//             } 
//           },
//           purchaseCount: { $sum: 1 }, // Count the number of purchases (cars) per user
//           basePurchaseCost: { $sum: { $toDouble: { $ifNull: ["$purchase_payment.base_purchase_cost", 0] } } }, // Sum of base_purchase_cost
//           shippingCost: { $sum: { $toDouble: { $ifNull: ["$shipping.cost", 0] } } }, // Sum of shipping.cost for profit calculation
//           markupShippingCost: { $sum: { $toDouble: { $ifNull: ["$shipping.Markup_shipping_cost", 0] } } } // Sum of Markup_shipping_cost
//         }
//       },
//       {
//         $lookup: {
//           from: 'users',
//           localField: '_id', // _id from $group is userId
//           foreignField: '_id', // Match with _id in users collection
//           as: 'user'
//         }
//       },
//       { $unwind: '$user' },
//       {
//         $project: {
//           _id: 0,
//           userId: '$_id',
//           username: '$user.username',
//           email: '$user.email',
//           purchaseTotal: 1,
//           shippingTotal: 1,
//           totalPaid: 1,
//           purchaseCount: 1,
//           // Formula: purchase_profit = |purchase_total - purchase_payment.base_purchase_cost|
//           purchaseProfit: { $abs: { $subtract: ['$purchaseTotal', '$basePurchaseCost'] } },
//           // Formula: shipping_profit = |shipping.cost - shipping.Markup_shipping_cost|
//           shippingProfit: { $abs: { $subtract: ['$shippingCost', '$markupShippingCost'] } },
//           // Formula: total_profit = purchase_profit + shipping_profit
//           totalProfit: { 
//             $add: [
//               { $abs: { $subtract: ['$purchaseTotal', '$basePurchaseCost'] } }, 
//               { $abs: { $subtract: ['$shippingCost', '$markupShippingCost'] } }
//             ]
//           }
//         }
//       }
//     ]);

//     // Log aggregated totals for each user and cross-check with manual totals
//     // console.log('Aggregated Totals by User:');
//     // totals.forEach((total) => {
//     //   const userId = total.userId.toString();
//     //   console.log(`User ${total.username Rollback to previous version? || 'undefined'} (ID: ${userId}):`);
//     //   console.log(`  Aggregated purchaseTotal: ${total.purchaseTotal} (Manual: ${manualTotals[userId]?.purchaseTotal || 'N/A'})`);
//     //   console.log(`  Aggregated shippingTotal: ${total.shippingTotal} (Manual: ${manualTotals[userId]?.shippingTotal || 'N/A'})`);
//     //   console.log(`  Aggregated totalPaid: ${total.totalPaid} (Manual: ${manualTotals[userId]?.totalPaid || 'N/A'})`);
//     //   console.log(`  Aggregated purchaseCount: ${total.purchaseCount} (Manual: ${manualTotals[userId]?.purchaseCount || 'N/A'})`);
//     //   console.log(`  Aggregated purchaseProfit: ${total.purchaseProfit} (Manual: ${manualTotals[userId]?.purchaseProfit || 'N/A'})`);
//     //   console.log(`  Aggregated shippingProfit: ${total.shippingProfit} (Manual: ${manualTotals[userId]?.shippingProfit || 'N/A'})`);
//     //   console.log(`  Aggregated totalProfit: ${total.totalProfit} (Manual: ${(manualTotals[userId]?.purchaseProfit + manualTotals[userId]?.shippingProfit) || 'N/A'})`);
//     // });

//     // Handle empty result
//     if (!totals || !totals.length) {
//       return res.status(404).json({
//         success: false,
//         message: 'No purchase totals found',
//       });
//     }

//     console.log("totals ", totals);

//     // Return result
//     return res.status(200).json({
//       success: true,
//       message: 'Purchase totals retrieved successfully',
//       data: totals,
//     });
//   } catch (error) {
//     console.error('Error fetching purchase totals by admin ID:', error);
//     return res.status(500).json({
//       success: false,
//       message: 'Server error while fetching purchase totals',
//       error: error.message,
//     });
//   }
// };




// const getProfitSummary = async (req, res) => {
//   try {
//     console.log("req.user.role:", req.user.role);
//     let filter = {};

//     // Role-based filtering
//     if (req.user.role === "admin") {
//       console.log("Admin role detected");
//       const targetUserId = req.body.id || "all";
//       // console.log("Target user ID:", targetUserId);

//       if (targetUserId === "all") {
//         const users = await model.User.find({ AdminId: req.user.id }).select('_id');
//         filter.userId = { $in: users.map(user => user._id) };
//         // console.log("Filter for all users:", filter);
//       } else {
//         if (!mongoose.Types.ObjectId.isValid(targetUserId)) {
//           // console.log("Invalid User ID format:", targetUserId);
//           return res.status(400).json({
//             success: false,
//             message: 'Invalid User ID format',
//           });
//         }
//         filter.userId = { $in: [targetUserId] };
//         // console.log("Filter for specific user:", filter);
//       }
//     } else {
//       console.log("Unauthorized access attempt");
//       return res.status(403).json({
//         success: false,
//         message: 'Unauthorized access',
//       });
//     }

//     console.log("Final filter:", filter);

//     // Fetch raw purchase data for manual calculation and logging
//     const rawPurchases = await model.Purchase.find(filter).populate('userId', 'username email');
//     console.log('Raw Purchase Data for Manual Verification:');
//     let manualTotals = {};

//     // rawPurchases.forEach((purchase, index) => {
//     //   const userId = purchase.userId?._id.toString() || 'undefined';
//     //   console.log(`Purchase ${index + 1} for User ${purchase.userId?.username || 'undefined'} (ID: ${userId}):`);
//     //   console.log(`  bid: ${purchase.bid} (type: ${typeof purchase.bid})`);
//     //   console.log(`  auctionFees: ${purchase.auctionFees} (type: ${typeof purchase.auctionFees})`);
//     //   console.log(`  purchase_payment.adjustment: ${purchase.purchase_payment.adjustment} (type: ${typeof purchase.purchase_payment.adjustment})`);
//     //   console.log(`  shipping.cost: ${purchase.shipping.cost} (type: ${typeof purchase.shipping.cost})`);
//     //   console.log(`  shipping.Markup_shipping_cost: ${purchase.shipping.Markup_shipping_cost} (type: ${typeof purchase.shipping.Markup_shipping_cost})`);
//     //   console.log(`  purchase_payment.paid: ${purchase.purchase_payment.paid} (type: ${typeof purchase.purchase_payment.paid})`);
//     //   console.log(`  shipping.paid: ${purchase.shipping.paid} (type: ${typeof purchase.shipping.paid})`);
//     //   console.log(`  purchase_payment.base_purchase_cost: ${purchase.purchase_payment.base_purchase_cost} (type: ${typeof purchase.purchase_payment.base_purchase_cost})`);

//     //   // Manual calculations
//     //   const purchaseTotal = (purchase.bid || 0) + (purchase.auctionFees || 0) + (purchase.purchase_payment.adjustment || 0);
//     //   const transportTotal = (purchase.shipping.cost || 0) + (purchase.shipping.Markup_shipping_cost || 0);
//     //   const totalPaid = (purchase.purchase_payment.paid || 0) + (purchase.shipping.paid || 0);
//     //   const purchaseProfit = Math.abs(purchaseTotal - (purchase.purchase_payment.base_purchase_cost || 0));
//     //   const transportProfit = Math.abs(transportTotal - (purchase.shipping.Markup_shipping_cost || 0));
//     //   const totalProfit = purchaseProfit + transportProfit;

//     //   console.log(`  Calculated purchase_total (bid + auctionFees + adjustment): ${purchaseTotal}`);
//     //   console.log(`  Calculated transport_total (shipping.cost + Markup_shipping_cost): ${transportTotal}`);
//     //   console.log(`  Calculated total_paid (purchase_payment.paid + shipping.paid): ${totalPaid}`);
//     //   console.log(`  Calculated purchase_profit (|purchase_total - base_purchase_cost|): ${purchaseProfit}`);
//     //   console.log(`  Calculated transport_profit (|transport_total - Markup_shipping_cost|): ${transportProfit}`);
//     //   console.log(`  Calculated total_profit (purchase_profit + transport_profit): ${totalProfit}`);

//     //   // Accumulate manual totals
//     //   if (!manualTotals[userId]) {
//     //     manualTotals[userId] = {
//     //       purchaseTotal: 0,
//     //       transportTotal: 0,
//     //       totalPaid: 0,
//     //       purchaseCount: 0,
//     //       basePurchaseCost: 0,
//     //       markupShippingCost: 0,
//     //       purchaseProfit: 0,
//     //       transportProfit: 0,
//     //       totalProfit: 0,
//     //     };
//     //   }
//     //   manualTotals[userId].purchaseTotal += purchaseTotal;
//     //   manualTotals[userId].transportTotal += transportTotal;
//     //   manualTotals[userId].totalPaid += totalPaid;
//     //   manualTotals[userId].purchaseCount += 1;
//     //   manualTotals[userId].basePurchaseCost += purchase.purchase_payment.base_purchase_cost || 0;
//     //   manualTotals[userId].markupShippingCost += purchase.shipping.Markup_shipping_cost || 0;
//     //   manualTotals[userId].purchaseProfit += purchaseProfit;
//     //   manualTotals[userId].transportProfit += transportProfit;
//     //   manualTotals[userId].totalProfit += totalProfit;
//     // });

//     // Log manual totals
//     // console.log('Manual Totals for Cross-Checking:');
//     // Object.keys(manualTotals).forEach((userId) => {
//     //   const totals = manualTotals[userId];
//     //   console.log(`User ID: ${userId}`);
//     //   console.log(`  Manual purchaseTotal: ${totals.purchaseTotal}`);
//     //   console.log(`  Manual transportTotal: ${totals.transportTotal}`);
//     //   console.log(`  Manual totalPaid: ${totals.totalPaid}`);
//     //   console.log(`  Manual purchaseCount: ${totals.purchaseCount}`);
//     //   console.log(`  Manual basePurchaseCost: ${totals.basePurchaseCost}`);
//     //   console.log(`  Manual markupShippingCost: ${totals.markupShippingCost}`);
//     //   console.log(`  Manual purchaseProfit: ${totals.purchaseProfit}`);
//     //   console.log(`  Manual transportProfit: ${totals.transportProfit}`);
//     //   console.log(`  Manual totalProfit: ${totals.totalProfit}`);
//     // });

//     // Aggregation with updated formulas and safe $convert usage
//     const totals = await model.Purchase.aggregate([
//       { $match: filter },
//       {
//         $group: {
//           _id: "$userId",
//           purchaseTotal: {
//             $sum: {
//               $add: [
//                 { $convert: { input: "$bid", to: "double", onError: 0, onNull: 0 } },
//                 { $convert: { input: "$auctionFees", to: "double", onError: 0, onNull: 0 } },
//                 { $convert: { input: "$purchase_payment.adjustment", to: "double", onError: 0, onNull: 0 } },
//               ],
//             },
//           },
//           transportTotal: {
//             $sum: {
//               $add: [
//                 { $convert: { input: "$shipping.cost", to: "double", onError: 0, onNull: 0 } },
//                 { $convert: { input: "$shipping.Markup_shipping_cost", to: "double", onError: 0, onNull: 0 } },
//               ],
//             },
//           },
//           totalPaid: {
//             $sum: {
//               $add: [
//                 { $convert: { input: "$purchase_payment.paid", to: "double", onError: 0, onNull: 0 } },
//                 { $convert: { input: "$shipping.paid", to: "double", onError: 0, onNull: 0 } },
//               ],
//             },
//           },
//           basePurchaseCost: {
//             $sum: {
//               $convert: { input: "$purchase_payment.base_purchase_cost", to: "double", onError: 0, onNull: 0 },
//             },
//           },
//           markupShippingCost: {
//             $sum: {
//               $convert: { input: "$shipping.Markup_shipping_cost", to: "double", onError: 0, onNull: 0 },
//             },
//           },
//           purchaseCount: { $sum: 1 },
//         },
//       },
//       {
//         $lookup: {
//           from: 'users',
//           localField: '_id',
//           foreignField: '_id',
//           as: 'user',
//         },
//       },
//       { $unwind: '$user' },
//       {
//         $project: {
//           _id: 0,
//           userId: '$_id',
//           username: '$user.username',
//           email: '$user.email',
//           purchaseTotal: 1,
//           transportTotal: 1,
//           totalPaid: 1,
//           purchaseCount: 1,
//           purchaseProfit: {
//             $abs: { $subtract: ["$purchaseTotal", "$basePurchaseCost"] },
//           },
//          transportProfit: {
//   $sum: {
//     $convert: { input: "$shipping.Markup_shipping_cost", to: "double", onError: 0, onNull: 0 },
//   },
// },
//           totalProfit: {
//             $add: [
//               { $abs: { $subtract: ["$purchaseTotal", "$basePurchaseCost"] } },
//               { $abs: { $subtract: ["$transportTotal", "$markupShippingCost"] } },
//             ],
//           },
//         },
//       },
//     ]);

//     // Log aggregated totals for cross-checking
//     console.log('Aggregated Totals from MongoDB:');
//     totals.forEach((total) => {
//       const userId = total.userId.toString();
//       console.log(`User ${total.username || 'undefined'} (ID: ${userId}):`);
//       console.log(`  Aggregated purchaseTotal: ${total.purchaseTotal} (Manual: ${manualTotals[userId]?.purchaseTotal || 'N/A'})`);
//       console.log(`  Aggregated transportTotal: ${total.transportTotal} (Manual: ${manualTotals[userId]?.transportTotal || 'N/A'})`);
//       console.log(`  Aggregated totalPaid: ${total.totalPaid} (Manual: ${manualTotals[userId]?.totalPaid || 'N/A'})`);
//       console.log(`  Aggregated purchaseCount: ${total.purchaseCount} (Manual: ${manualTotals[userId]?.purchaseCount || 'N/A'})`);
//       console.log(`  Aggregated purchaseProfit: ${total.purchaseProfit} (Manual: ${manualTotals[userId]?.purchaseProfit || 'N/A'})`);
//       console.log(`  Aggregated transportProfit: ${total.transportProfit} (Manual: ${manualTotals[userId]?.transportProfit || 'N/A'})`);
//       console.log(`  Aggregated totalProfit: ${total.totalProfit} (Manual: ${manualTotals[userId]?.totalProfit || 'N/A'})`);
//     });

//     if (!totals || totals.length === 0) {
//       console.log("No purchase totals found");
//       return res.status(404).json({
//         success: false,
//         message: 'No purchase totals found',
//       });
//     }

//     console.log("Final aggregated totals:", totals);
//     return res.status(200).json({
//       success: true,
//       message: 'Purchase totals retrieved successfully',
//       data: totals,
//     });

//   } catch (error) {
//     console.error('Error fetching purchase totals:', error);
//     return res.status(500).json({
//       success: false,
//       message: 'Server error while fetching purchase totals',
//       error: error.message,
//     });
//   }
// };



const getProfitSummary = async (req, res) => {
  try {
    console.log("req.user.role:", req.user.role);
    let filter = {};

    // Role-based filtering
    if (req.user.role === "admin") {
      console.log("Admin role detected");
      const targetUserId = req.body.id || "all";
      if (targetUserId === "all") {
        const users = await model.User.find({ AdminId: req.user.id }).select('_id');
        filter.userId = { $in: users.map(user => user._id) };
      } else {
        if (!mongoose.Types.ObjectId.isValid(targetUserId)) {
          return res.status(400).json({
            success: false,
            message: 'Invalid User ID format',
          });
        }
        filter.userId = { $in: [targetUserId] };
      }
    } else {
      return res.status(403).json({
        success: false,
        message: 'Unauthorized access',
      });
    }

    console.log("Final filter:", filter);

    // Aggregation with updated formulas
    const totals = await model.Purchase.aggregate([
      { $match: filter },
      {
        $group: {
          _id: "$userId",
          purchaseTotal: {
            $sum: {
              $add: [
                { $convert: { input: "$bid", to: "double", onError: 0, onNull: 0 } },
                { $convert: { input: "$auctionFees", to: "double", onError: 0, onNull: 0 } },
                { $convert: { input: "$purchase_payment.adjustment", to: "double", onError: 0, onNull: 0 } },
              ],
            },
          },
          transportTotal: {
            $sum: {
              $add: [
                { $convert: { input: "$shipping.cost", to: "double", onError: 0, onNull: 0 } },
                { $convert: { input: "$shipping.Markup_shipping_cost", to: "double", onError: 0, onNull: 0 } },
              ],
            },
          },
          totalPaid: {
            $sum: {
              $add: [
                { $convert: { input: "$purchase_payment.paid", to: "double", onError: 0, onNull: 0 } },
                { $convert: { input: "$shipping.paid", to: "double", onError: 0, onNull: 0 } },
              ],
            },
          },
          basePurchaseCost: {
            $sum: {
              $convert: { input: "$purchase_payment.base_purchase_cost", to: "double", onError: 0, onNull: 0 },
            },
          },
          markupShippingCost: {
            $sum: {
              $convert: { input: "$shipping.Markup_shipping_cost", to: "double", onError: 0, onNull: 0 },
            },
          },
          purchaseCount: { $sum: 1 },
        },
      },
      {
        $lookup: {
          from: 'users',
          localField: '_id',
          foreignField: '_id',
          as: 'user',
        },
      },
      { $unwind: '$user' },
      {
        $project: {
          _id: 0,
          userId: '$_id',
          username: '$user.username',
          email: '$user.email',
          purchaseTotal: 1,
          transportTotal: 1,
          totalPaid: 1,
          purchaseCount: 1,
          purchaseProfit: {
            $abs: { $subtract: ["$purchaseTotal", "$basePurchaseCost"] },
          },
          transportProfit: "$markupShippingCost",
          totalProfit: {
            $add: [
              { $abs: { $subtract: ["$purchaseTotal", "$basePurchaseCost"] } },
              "$markupShippingCost",
            ],
          },
        },
      },
    ]);

    // Log aggregated totals for cross-checking
    console.log('Aggregated Totals from MongoDB:');
    totals.forEach((total) => {
      console.log(`User ${total.username || 'undefined'} (ID: ${total.userId}):`);
      console.log(`  Aggregated purchaseTotal: ${total.purchaseTotal}`);
      console.log(`  Aggregated transportTotal: ${total.transportTotal}`);
      console.log(`  Aggregated totalPaid: ${total.totalPaid}`);
      console.log(`  Aggregated purchaseCount: ${total.purchaseCount}`);
      console.log(`  Aggregated purchaseProfit: ${total.purchaseProfit}`);
      console.log(`  Aggregated transportProfit: ${total.transportProfit}`);
      console.log(`  Aggregated totalProfit: ${total.totalProfit}`);
    });

    if (!totals || totals.length === 0) {
      console.log("No purchase totals found");
      return res.status(404).json({
        success: false,
        message: 'No purchase totals found',
      });
    }

    console.log("Final aggregated totals:", totals);
    return res.status(200).json({
      success: true,
      message: 'Purchase totals retrieved successfully',
      data: totals,
    });

  } catch (error) {
    console.error('Error fetching purchase totals:', error);
    return res.status(500).json({
      success: false,
      message: 'Server error while fetching purchase totals',
      error: error.message,
    });
  }
};

const updatePurchaseCosts = async (req, res) => {
  try {
    console.log("data pases", req.body);
    
    const { purchaseId, base_purchase_cost, base_shipping_cost } = req.body;

    // Validate purchaseId
    if (!mongoose.Types.ObjectId.isValid(purchaseId)) {
      return res.status(400).json({
        success: false,
        message: 'Invalid Purchase ID format',
      });
    }

    // Validate inputs
    if (base_purchase_cost < 0 || base_shipping_cost < 0) {
      return res.status(400).json({
        success: false,
        message: 'Base costs cannot be negative',
      });
    }

    // Check if user is authorized (admin role)
    if (req.user.role !== "admin") {
      return res.status(403).json({
        success: false,
        message: 'Unauthorized access',
      });
    }

    // Update the purchase document
    const updatedPurchase = await Purchase.findByIdAndUpdate(
      purchaseId,
      {
        $set: {
          "purchase_payment.base_purchase_cost": base_purchase_cost,
          "shipping.base_shipping_cost": base_shipping_cost,
        },
      },
      { new: true }
    );

    if (!updatedPurchase) {
      return res.status(404).json({
        success: false,
        message: 'Purchase not found',
      });
    }

    return res.status(200).json({
      success: true,
      message: 'Purchase costs updated successfully',
      data: updatedPurchase,
    });
  } catch (error) {
    console.error('Error updating purchase costs:', error);
    return res.status(500).json({
      success: false,
      message: 'Server error while updating purchase costs',
      error: error.message,
    });
  }
};

const updatePurchaseFields = async (req, res) => {
  try {
    console.log("req body is ", req.body);

    const { id, ...updates } = req.body;

    console.log("Update request body:", updates);

    // 🔒 Validate ID
    if (!id || !mongoose.Types.ObjectId.isValid(id)) {
      return res.status(400).json({
        success: false,
        message: "Valid purchase ID is required",
      });
    }

    // ✅ Define allowed fields
    const allowedFields = [
      'vehicle_type',
      'Vin',
      'containerNumber',
      'lotNumber',
      'bid',
      'auctionFees',
      'shippingPort',
      'photoUrl',
      'shipping.cost',
      'shipping.paid',
      'shipping.Markup_shipping_cost',
      'shipping.total_cost',
      'shipping.arrival',
      'purchase_payment.due',
      'purchase_payment.paid',
      'purchase_payment.Markup_purchase_cost',
      'purchase_payment.adjustment',
      'purchase_payment.base_purchase_cost'
    ];

    // 🔄 Flattened keys to nested path mapping
    const purchasePaymentFields = [
      'due', 'paid', 'Markup_purchase_cost', 'adjustment', 'base_purchase_cost'
    ];

    const shippingFields = [
      'cost', 'paid', 'Markup_shipping_cost', 'total_cost', 'arrival'
    ];

    const updatePayload = {};

    for (const key in updates) {
      const value = updates[key];
      if (value === undefined || value === null || value === '') continue;

      // 🔧 Handle purchase_payment flat fields
      if (purchasePaymentFields.includes(key)) {
        if (!updatePayload.purchase_payment) updatePayload.purchase_payment = {};
        updatePayload.purchase_payment[key] = value;
      }

      // 🔧 Handle shipping flat fields
      else if (shippingFields.includes(key)) {
        if (!updatePayload.shipping) updatePayload.shipping = {};
        updatePayload.shipping[key] = value;
      }

      // 🔧 Handle allowed nested fields like 'shipping.cost'
      else if (allowedFields.includes(key)) {
        if (key.includes(".")) {
          const [parent, child] = key.split(".");
          if (!updatePayload[parent]) updatePayload[parent] = {};
          updatePayload[parent][child] = value;
        } else {
          updatePayload[key] = value;
        }
      }
    }

    if (Object.keys(updatePayload).length === 0) {
      return res.status(400).json({
        success: false,
        message: "No valid fields provided for update",
      });
    }

    // 🛠️ Perform update
    const updatedPurchase = await model.Purchase.findByIdAndUpdate(
      id,
      { $set: updatePayload },
      { new: true, runValidators: true }
    );

    if (!updatedPurchase) {
      return res.status(404).json({
        success: false,
        message: "Purchase not found",
      });
    }

    return res.status(200).json({
      success: true,
      message: "Purchase details updated successfully",
      data: updatedPurchase,
    });

  } catch (error) {
    console.error("Error in generic update:", error);
    return res.status(500).json({
      success: false,
      message: "Server error while updating purchase details",
      error: error.message,
    });
  }
};
module.exports = { createPurchase, getPurchasesByAdminId, UpdatePurchase ,getSearchHistory,getCurrentBid,uploadImages,UpdatePurchaseDetails,getProfitSummary,updatePurchaseCosts,updatePurchaseFields}; 