import express from "express";
import Coupon from "../models/coupon.js";
import { User } from "../models/user.js";
import { authenticate } from "../middleware/authMiddleware.js";
const router = express.Router();


// Route to CREATE a new coupon
router.post("/create", async (req, res) => {
  try {
    const { code, discountType, discountAmount, serviceType, validFrom, validUntil, maxUsage, isActive } = req.body;
    
    // Check if coupon with same code already exists
    const existingCoupon = await Coupon.findOne({ code });
    if (existingCoupon) {
      return res.status(400).json({ error: "Coupon code already exists" });
    }

    const newCoupon = new Coupon({
      code,
      discountType,
      discountAmount,
      serviceType,
      validFrom: validFrom || new Date(),
      validUntil,
      maxUsage,
      isActive: isActive !== undefined ? isActive : true
    });

    await newCoupon.save();
    res.status(201).json({ 
      message: "Coupon created successfully", 
      coupon: newCoupon 
    });

  } catch (err) {
    if (err.message.includes('validUntil must be later than validFrom')) {
      return res.status(400).json({ error: err.message });
    }
    res.status(500).json({ error: "Server error creating coupon", details: err.message });
  }
});

// Route to VALIDATE and CHECK a coupon (not apply it yet)
router.post("/validate", authenticate, async (req, res) => {
  const { couponCode, serviceType } = req.body;
  const userId = req.user.id;
  
  try {
    // Find the coupon
    const coupon = await Coupon.findOne({ code: couponCode, isActive: true });

    if (!coupon) {
      return res.json({
        isValid: false,
        message: "Coupon is invalid or inactive",
      });
    }

    // Check if the coupon is expired
    if (new Date(coupon.validUntil) < new Date()) {
      return res.json({ 
        isValid: false, 
        message: "Coupon has expired" 
      });
    }

    // Check if the coupon usage limit has been reached globally
    if (coupon.usageCount >= coupon.maxUsage) {
      return res.json({
        isValid: false,
        message: "Coupon usage limit reached",
      });
    }

    // Check if the coupon applies to the requested service type
    if (!coupon.serviceType.includes(serviceType)) {
      return res.json({
        isValid: false,
        message: `This coupon is not valid for ${serviceType}. Valid for: ${coupon.serviceType.join(', ')}`,
      });
    }

    // Check if the user has already used this coupon
    const user = await User.findById(userId);
    const hasUsedCoupon = user.usedCoupons?.some(
      usedCoupon => usedCoupon.code === couponCode
    );

    if (hasUsedCoupon) {
      return res.json({
        isValid: false,
        message: "You have already used this coupon. Each coupon can only be used once per account.",
      });
    }

    // Check if this user has already used this coupon (also check coupon's usedBy array)
    if (coupon.usedBy.includes(userId)) {
      return res.json({
        isValid: false,
        message: "You have already used this coupon. Each coupon can only be used once per account.",
      });
    }

    // If all checks pass, return the coupon details
    res.json({
      isValid: true,
      discount: coupon.discountAmount,
      discountType: coupon.discountType,
      serviceType: coupon.serviceType,
      message: coupon.discountType === 'free' 
        ? "Coupon applied successfully - 100% discount!" 
        : `Coupon applied successfully - ${coupon.discountAmount}% off!`,
    });
  } catch (err) {
    console.error('Coupon validation error:', err);
    res.status(500).json({ error: "Server error validating coupon" });
  }
});

// Route to APPLY a coupon (mark as used by the user)
router.post("/apply", authenticate, async (req, res) => {
  const { couponCode, serviceType } = req.body;
  const userId = req.user.id;
  
  try {
    // Find the coupon
    const coupon = await Coupon.findOne({ code: couponCode, isActive: true });

    if (!coupon) {
      return res.status(400).json({
        success: false,
        message: "Coupon is invalid or inactive",
      });
    }

    // Check if the coupon is expired
    if (new Date(coupon.validUntil) < new Date()) {
      return res.status(400).json({ 
        success: false, 
        message: "Coupon has expired" 
      });
    }

    // Check if the coupon usage limit has been reached
    if (coupon.usageCount >= coupon.maxUsage) {
      return res.status(400).json({
        success: false,
        message: "Coupon usage limit reached",
      });
    }

    // Check if the coupon applies to the requested service type
    if (!coupon.serviceType.includes(serviceType)) {
      return res.status(400).json({
        success: false,
        message: `This coupon is not valid for ${serviceType}`,
      });
    }

    // Check if the user has already used this coupon
    const user = await User.findById(userId);
    const hasUsedCoupon = user.usedCoupons?.some(
      usedCoupon => usedCoupon.code === couponCode
    );

    if (hasUsedCoupon || coupon.usedBy.includes(userId)) {
      return res.status(400).json({
        success: false,
        message: "You have already used this coupon",
      });
    }

    // Apply the coupon: increment usage count and add user to usedBy array
    const updatedCoupon = await Coupon.findOneAndUpdate(
      { _id: coupon._id },
      { 
        $inc: { usageCount: 1 },
        $push: { usedBy: userId }
      },
      { new: true }
    );

    // Add coupon to user's usedCoupons array
    await User.findByIdAndUpdate(
      userId,
      {
        $push: {
          usedCoupons: {
            couponId: coupon._id,
            code: couponCode,
            usedAt: new Date(),
            serviceType: serviceType,
            discountAmount: coupon.discountAmount
          }
        }
      }
    );

    res.json({
      success: true,
      discount: updatedCoupon.discountAmount,
      discountType: updatedCoupon.discountType,
      message: "Coupon applied successfully",
      coupon: {
        code: updatedCoupon.code,
        discountAmount: updatedCoupon.discountAmount,
        discountType: updatedCoupon.discountType
      }
    });
  } catch (err) {
    console.error('Coupon application error:', err);
    res.status(500).json({ 
      success: false, 
      error: "Server error applying coupon" 
    });
  }
});

// Route to GET user's used coupons
router.get("/my-coupons", authenticate, async (req, res) => {
  try {
    const userId = req.user.id;
    const user = await User.findById(userId).select('usedCoupons');
    
    res.json({
      success: true,
      usedCoupons: user.usedCoupons || []
    });
  } catch (err) {
    console.error('Error fetching user coupons:', err);
    res.status(500).json({ 
      success: false, 
      error: "Server error fetching coupons" 
    });
  }
});
export default router;
