Error fetching workouts: TypeError: Cannot read properties of undefined (reading 'toString')
    at exports.getUserWorkouts (D:\apps\Fitness-app\backend\controllers\workoutsController.js:14:32)
    at Layer.handle [as handle_request] (D:\apps\Fitness-app\backend\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\apps\Fitness-app\backend\node_modules\express\lib\router\route.js:149:13)
    at authMiddleware (D:\apps\Fitness-app\backend\middleware\authMiddleware.js:30:9)
    at Layer.handle [as handle_request] (D:\apps\Fitness-app\backend\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\apps\Fitness-app\backend\node_modules\express\lib\router\route.js:149:13)
    at Route.dispatch (D:\apps\Fitness-app\backend\node_modules\express\lib\router\route.js:119:3)
    at Layer.handle [as handle_request] (D:\apps\Fitness-app\backend\node_modules\express\lib\router\layer.js:95:5)
    at D:\apps\Fitness-app\backend\node_modules\express\lib\router\index.js:284:15
    at Function.process_params (D:\apps\Fitness-app\backend\node_modules\express\lib\router\index.js:346:12)
::ffff:10.0.0.218 - - [08/Oct/2024:18:52:07 +0000] "GET /api/workouts?userId=66ff4c3d7a99bdf2f7ac6024&month=2024-10&categories=Cardio,StrengthTraining,Flexibility HTTP/1.1" 500 26 "-" "okhttp/4.9.2"

// backend/controllers/workoutsController.js

const Workout = require('../models/Workout'); // Ensure the Workout model is correctly defined
const moment = require('moment');

/**
 * Get workouts for a user based on query parameters.
 */
exports.getUserWorkouts = async (req, res) => {
  try {
    const { month, categories, muscleGroup } = req.query;

    // 1. Derive userId from authenticated user
    if (!req.user || !req.user.id) {
      console.warn('Unauthorized access: req.user is missing.');
      return res.status(401).json({ message: 'Unauthorized: User information missing.' });
    }
    const userId = req.user.id;

    // 2. Validate and parse the month parameter
    if (!month) {
      return res.status(400).json({ message: 'month query parameter is required.' });
    }

    const parsedMonth = moment(month, 'YYYY-MM', true);
    if (!parsedMonth.isValid()) {
      return res.status(400).json({ message: 'Invalid month format. Use YYYY-MM.' });
    }

    // 3. Define default categories
    const defaultCategories = ['Cardio', 'StrengthTraining', 'Flexibility'];
    let selectedCategories = defaultCategories;

    // 4. Filter by categories if provided
    if (categories) {
      selectedCategories = categories.split(',').map((cat) => cat.trim());
      // Validate selectedCategories against defaultCategories
      const validCategories = selectedCategories.filter((cat) => defaultCategories.includes(cat));
      if (validCategories.length === 0) {
        return res.status(400).json({ message: 'No valid categories provided.' });
      }
      selectedCategories = validCategories;
    }

    // 5. Build the query object
    const query = {
      user: userId,
      date: {
        $gte: parsedMonth.clone().startOf('month').toDate(),
        $lte: parsedMonth.clone().endOf('month').toDate(),
      },
      category: { $in: selectedCategories },
    };

    // 6. Further filter by muscle group if provided and category is StrengthTraining
    if (muscleGroup && muscleGroup !== 'All') {
      // Fetch workouts that are either StrengthTraining with the specified muscleGroup or not StrengthTraining
      query.$or = [
        { category: 'StrengthTraining', muscleGroup: muscleGroup },
        { category: { $ne: 'StrengthTraining' } },
      ];
    }

    // 7. Fetch workouts from the database
    const workouts = await Workout.find(query)
      .populate('user', '-password') // Exclude password and populate if needed
      .lean(); // Returns plain JavaScript objects

    // 8. Structure data as per frontend expectations
    const structuredData = {};

    workouts.forEach((workout) => {
      // Ensure that the workout has a valid date
      if (workout.date) {
        const dateStr = moment(workout.date).format('YYYY-MM-DD');
        if (!structuredData[workout.category]) {
          structuredData[workout.category] = {};
        }
        structuredData[workout.category][dateStr] = workout;
      } else {
        console.warn(`Workout with ID ${workout._id} is missing a date.`);
      }
    });

    res.json(structuredData);
  } catch (error) {
    console.error('Error fetching workouts:', error);
    res.status(500).json({ message: 'Server Error' });
  }
};

/**
 * Create a new workout
 */
exports.createWorkout = async (req, res) => {
  try {
    const { category, date, ...rest } = req.body;

    // Validate category
    const allowedCategories = ['Cardio', 'StrengthTraining', 'Flexibility'];
    if (!allowedCategories.includes(category)) {
      return res.status(400).json({ message: 'Invalid category provided.' });
    }

    // Prepare workout data
    const workoutData = {
      user: req.user.id,
      category,
      date,
      ...rest,
    };

    // Create workout
    const newWorkout = new Workout(workoutData);
    await newWorkout.save();

    res.status(201).json(newWorkout);
  } catch (error) {
    console.error('Error creating workout:', error);
    res.status(500).json({ message: 'Server Error' });
  }
};

/**
 * Update an existing workout
 */
exports.updateWorkout = async (req, res) => {
  try {
    const workoutId = req.params.id;
    const updates = req.body;

    // Find the workout
    const workout = await Workout.findById(workoutId);
    if (!workout) {
      return res.status(404).json({ message: 'Workout not found.' });
    }

    // Check if the workout belongs to the authenticated user
    if (workout.user.toString() !== req.user.id) {
      return res.status(403).json({ message: 'Forbidden: You cannot modify this workout.' });
    }

    // Update workout
    Object.assign(workout, updates);
    await workout.save();

    res.json(workout);
  } catch (error) {
    console.error('Error updating workout:', error);
    res.status(500).json({ message: 'Server Error' });
  }
};

/**
 * Delete a workout
 */
exports.deleteWorkout = async (req, res) => {
  try {
    const workoutId = req.params.id;

    // Find the workout
    const workout = await Workout.findById(workoutId);
    if (!workout) {
      return res.status(404).json({ message: 'Workout not found.' });
    }

    // Check if the workout belongs to the authenticated user
    if (workout.user.toString() !== req.user.id) {
      return res.status(403).json({ message: 'Forbidden: You cannot delete this workout.' });
    }

    // Delete workout
    await workout.remove();

    res.json({ message: 'Workout deleted successfully.' });
  } catch (error) {
    console.error('Error deleting workout:', error);
    res.status(500).json({ message: 'Server Error' });
  }
};