const Order = require("../models/orderModel");
const Course = require("../models/courseModel");
const Coupon = require("../models/couponModel");
const User = require("../models/userModel"); // Assuming you have this
const APIFeatures = require("../utils/ApiFeatures");

// --- Helper: Verify Coupon Logic ---
const verifyCoupon = async (code, user) => {
  const coupon = await Coupon.findOne({ code: code, isActive: true });

  if (!coupon) throw new Error("Invalid Coupon Code");
  if (coupon.expiresAt < Date.now()) throw new Error("Coupon has expired");
  if (coupon.usedCount >= coupon.maxUses)
    throw new Error("Coupon usage limit reached");

  return coupon;
};

// 1. Create Order (The "Purchase" Action)
exports.createOrder = async (req, res) => {
  try {
    const { courseId, couponCode, paymentMethod } = req.body;

    // A. Fetch Course
    const course = await Course.findById(courseId);
    if (!course) throw new Error("Course not found");

    // B. Initial Prices
    let price = course.price;
    let discount = 0;
    let finalPrice = price;

    // C. Check Coupon if provided
    if (couponCode) {
      const coupon = await verifyCoupon(couponCode);

      // Calculate Discount (Percentage)
      const discountAmount = (price * coupon.discount) / 100;
      discount = discountAmount;
      finalPrice = price - discountAmount;

      // Update Coupon Usage
      coupon.usedCount += 1;
      await coupon.save();
    }

    // D. Create Order with Embeds (Snapshot)
    // We rely on req.user (from authController.protect)
    const newOrder = await Order.create({
      user: {
        _id: req.user._id,
        name: req.user.name,
        email: req.user.email,
      },
      course: {
        _id: course._id,
        name: course.name,
        price: course.price,
        coverImage: course.coverImage,
      },
      price,
      discount,
      finalPrice,
      couponApplied: couponCode || null,
      paymentMethod,
      status: "completed", // Or 'pending' if you integrate Stripe/PayPal later
    });

    // Optional: Add course to User's "myCourses" array if your User model has it
    // await User.findByIdAndUpdate(req.user._id, { $addToSet: { myCourses: course._id } });

    res.status(201).json({
      status: "success",
      data: { order: newOrder },
    });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};

// 2. Get All Orders (Admin)
exports.getAllOrders = async (req, res) => {
  try {
    const features = new APIFeatures(Order.find(), req.query)
      .filter()
      .sort()
      .paginate();
    const orders = await features.query;

    res.status(200).json({
      status: "success",
      results: orders.length,
      data: { orders },
    });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};

// 3. Get My Orders (Logged in User)
exports.getMyOrders = async (req, res) => {
  try {
    const orders = await Order.find({ "user._id": req.user._id }).sort(
      "-createdAt"
    );

    res.status(200).json({
      status: "success",
      results: orders.length,
      data: { orders },
    });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};
