export const updateAddress = async (req, res, next) => {
  const userId = req.user._id;
  const { addressId } = req.params;
  const updateData = req.body;

  if (!mongoose.Types.ObjectId.isValid(addressId)) {
    return res.status(400).json({ status: false, code: 400, message: 'Invalid address ID format' });
  }

  try {
    const address = await Address.findOne({ _id: addressId, user: userId });
    if (!address) {
      return res.status(404).json({ status: false, code: 404, message: 'Address not found or does not belong to user' });
    }

    // Create the potential final state of the address after update
    const mergedData = { ...address.toObject(), ...updateData }; // Combine existing and updates

    if (mergedData.label === 'Other') {
      if (!mergedData.customLabel) {
        return res.status(400).json({
          status: false,
          code: 400,
          message: 'Custom label is required when label is Other.'
        });
      }

      const existingCustomLabel = await Address.findOne({
        user: userId,
        customLabel: mergedData.customLabel,
        _id: { $ne: addressId } // exclude current address
      });

      if (existingCustomLabel) {
        return res.status(409).json({
          status: false,
          code: 409,
          message: `An 'Other' address named '${mergedData.customLabel}' already exists.`
        });
      }
    }

    const conditionalErrors = validateCarLocationDetails(mergedData);
    if (conditionalErrors) {
      return res.status(400).json({
        status: false,
        code: 400,
        message: 'Validation failed for conditional fields based on the update.',
        errors: conditionalErrors
      });
    }

    // Handle 'isPrimary' flag update (existing logic seems ok)
    if (updateData.hasOwnProperty('isPrimary')) {
      if (updateData.isPrimary === true && !address.isPrimary) {
        address.isPrimary = true; // Hook will handle uniqueness
      } else if (updateData.isPrimary === false && address.isPrimary) {
        // Trying to unset the primary flag
        const otherAddressesCount = await Address.countDocuments({ user: userId, _id: { $ne: addressId } });
        if (otherAddressesCount === 0) {
          // This is the only address, cannot unset primary
          return res.status(400).json({ status: false, code: 400, message: 'Cannot unset primary status for the only address.' });
        } else {
          // Prevent unsetting primary directly. Force setting another as primary.
          return res.status(400).json({ status: false, code: 400, message: 'Cannot unset primary. Please set another address as primary first.' });
        }
      }
      // If updateData.isPrimary is false and address.isPrimary is already false, or
      // if updateData.isPrimary is true and address.isPrimary is already true, no special action needed for isPrimary itself.
    }

    // Update other fields provided in updateData
    Object.keys(updateData).forEach(key => {
      if (key !== 'isPrimary' && key !== 'user' && key !== '_id') {
        // Allow setting fields to null if provided in updateData (for clearing)
        address[key] = updateData[key];
      }
    });

    const updatedAddress = await address.save(); // Pre-save hook handles primary

    res.status(200).json({
      status: true,
      code: 200,
      message: 'Address updated successfully',
      address: updatedAddress
    });

  } catch (error) {
    next(error);
  }
};

protectedRouter.route('/addresses/:addressId')
    .put(validateBody(updateAddressSchema), updateAddress)



export const updateAddressSchema = Joi.object({
  label: Joi.string().valid('Home', 'Office', 'Other').optional(),
  customLabel: Joi.string().trim().optional().allow('').messages({
    'string.base': 'Custom label must be a string',
  }),
  address: Joi.string().trim().optional(),
  addressLine2: Joi.string().trim().allow('').optional(),
  entryMethod: Joi.string().valid('current', 'manual').optional(),
  city: Joi.string().trim().optional(),
  carLocationType: Joi.string().valid(...carLocationTypeValues).optional(),
  ensureGarageUnlocked: Joi.boolean().optional(),
  garageAccessInstructions: Joi.string().trim().allow('', null).optional(),
  confirmSecurityNotification: Joi.boolean().optional(),
  waterAccess: Joi.string().valid(...waterAccessOptions).allow(null).optional(),
  parkingSpaceNumber: Joi.string().trim().allow('', null).optional(),
  parkingFloor: Joi.string().trim().allow('', null).optional(),
  carFindingDirections: Joi.string().trim().allow('', null).optional(),
  otherLocationDetails: Joi.string().trim().allow('', null).optional(),
  preferredWashType: Joi.string().valid(...washPreferenceOptions).optional(),
  additionalInfo: Joi.string().trim().allow('', null).optional(),
  location: Joi.object({
    type: Joi.string().valid('Point').default('Point'),
    coordinates: Joi.array().items(Joi.number()).length(2).required()
  }).optional(),
  isPrimary: Joi.boolean().optional(),
}).min(1).messages({ // Ensure at least one field is provided for update
  'object.min': 'At least one field must be provided for update.'
});



give example json for testing