const Cart = require('../models/Cart');
const Item = require('../models/Item');
const { ErrorResponse } = require('../utils/errorResponse');
const asyncHandler = require('../middleware/async');

/**
 * @desc    Check if cart contains prescription items
 * @route   GET /api/cart/check-prescription
 * @access  Private
 */
exports.checkPrescriptionRequired = asyncHandler(async (req, res, next) => {
  const userId = req.user.id;

  // Find the user's cart
  const cart = await Cart.findOne({ user: userId }).populate({
    path: 'items.item',
    select: 'requiresPrescription'
  });

  if (!cart) {
    return res.status(200).json({
      success: true,
      requiresPrescription: false,
      message: 'Cart is empty'
    });
  }

  // Check if any item in the cart requires a prescription
  const requiresPrescription = cart.items.some(
    cartItem => cartItem.item && cartItem.item.requiresPrescription
  );

  res.status(200).json({
    success: true,
    requiresPrescription,
    message: requiresPrescription 
      ? 'Cart contains items that require a prescription' 
      : 'No prescription required for items in cart'
  });
});

/**
 * @desc    Update cart with prescription information
 * @route   PUT /api/cart/:id/prescription
 * @access  Private
 */
exports.updateCartWithPrescription = asyncHandler(async (req, res, next) => {
  const { id: cartId } = req.params;
  const { prescriptionId, status } = req.body;
  const userId = req.user.id;

  // Validate input
  if (!prescriptionId || !status) {
    return next(new ErrorResponse('Please provide prescription ID and status', 400));
  }

  // Find and update the cart
  const cart = await Cart.findOneAndUpdate(
    { _id: cartId, user: userId },
    { 
      $set: { 
        'prescriptionInfo.id': prescriptionId,
        'prescriptionInfo.status': status,
        'prescriptionInfo.verifiedAt': status === 'verified' ? Date.now() : null,
        'prescriptionInfo.verifiedBy': status === 'verified' ? req.user.id : null
      } 
    },
    { new: true, runValidators: true }
  );

  if (!cart) {
    return next(new ErrorResponse('Cart not found', 404));
  }

  res.status(200).json({
    success: true,
    data: cart,
    message: `Prescription ${status} successfully`
  });
});

module.exports = exports;
