import Stripe from "stripe";
import express from "express";
import dotenv from "dotenv";
import Subscription from "../models/Subscription.js";
import jwt from "jsonwebtoken";
import { User } from "../models/usermodels.js";

dotenv.config();

const router = express.Router();
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

// ✅ Auth middleware
const authPayment = async (req, res, next) => {
  try {
    let token = req.cookies?.token;
    if (!token) {
      const authHeader = req.headers.authorization;
      if (authHeader && authHeader.startsWith("Bearer ")) {
        token = authHeader.split(" ")[1];
      }
    }
    if (!token) return res.status(401).json({ message: "Please login to access this resource" });
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = await User.findById(decoded.id);
    if (!req.user) return res.status(401).json({ message: "User not found" });
    next();
  } catch (err) {
    return res.status(401).json({ message: "Please login to access this resource" });
  }
};

// ✅ Subscription Checkout
router.post("/create-checkout-session", authPayment, async (req, res) => {
  const { priceId, planType } = req.body;
  try {
    const session = await stripe.checkout.sessions.create({
      mode: "subscription",
      payment_method_types: ["card"],
      line_items: [{ price: priceId, quantity: 1 }],
      metadata: { planType },
      success_url: `${process.env.CLIENT_URL}/success?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${process.env.CLIENT_URL}/packages`,
    });

    const expiresAt = new Date();
    if (planType === "monthly") {
      expiresAt.setMonth(expiresAt.getMonth() + 1);
    } else {
      expiresAt.setFullYear(expiresAt.getFullYear() + 1);
    }

    const planDetails = planType === "monthly"
      ? { name: "monthly", price: 39, description: "Base Subscription", lessonCount: 1, durationMinutes: 60,
          features: ["10% off 1 Hour Lessons", "20% off streamed Concerts", "$5 off Merch", "Full Access to music catalog", "Access to Monthly newsletter", "Early Access to Drops"] }
      : { name: "yearly", price: 79.99, description: "VIP Subscription", lessonCount: 12, durationMinutes: 60,
          features: ["20% off 1 hour Lesson", "Unlimited Replays on lessons", "35% off music streamed concerts", "$5 off merch", "Full Access to Music", "Honorary member discounts", "Early Access to Drops"] };

    await Subscription.findOneAndUpdate(
      { user: req.user._id },
      { user: req.user._id, subscription: planDetails, price: planDetails.price, paymentStatus: "paid", paymentIntentId: session.id, purchasedAt: new Date(), expiresAt, usedLessons: 0 },
      { upsert: true, new: true }
    );

    res.json({ sessionId: session.id, url: session.url });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// ✅ One-time Lesson Checkout
router.post("/create-lesson-checkout", authPayment, async (req, res) => {
  const { teacherId, teacherName, duration, finalPrice, originalPrice, discountRate, date, time, studentId } = req.body;

  try {
    const amountInCents = Math.round(finalPrice * 100);

    const session = await stripe.checkout.sessions.create({
      mode: "payment",
      payment_method_types: ["card"],
      line_items: [{
        price_data: {
          currency: "usd",
          unit_amount: amountInCents,
          product_data: {
            name: `Music Lesson with ${teacherName}`,
            description: `${duration} minute lesson on ${date} at ${time}${discountRate > 0 ? ` — ${Math.round(discountRate * 100)}% discount applied` : ""}`,
          },
        },
        quantity: 1,
      }],
      metadata: {
        teacherId,
        studentId: studentId || req.user._id.toString(),
        duration: duration.toString(),
        date,
        time,
        originalPrice: originalPrice.toString(),
        discountRate: discountRate.toString(),
        finalPrice: finalPrice.toString(),
      },
      success_url: `${process.env.CLIENT_URL}/dashboard/student/booking-success?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${process.env.CLIENT_URL}/dashboard/student/teachers`,
    });

    console.log("✅ Lesson checkout created:", teacherName, date, time);
    res.json({ url: session.url, sessionId: session.id });
  } catch (err) {
    console.error("❌ Lesson checkout error:", err.message);
    res.status(500).json({ message: err.message });
  }
});

// ✅ Verify Stripe lesson payment + create booking ONCE
router.post("/verify-lesson-payment", authPayment, async (req, res) => {
  const { sessionId } = req.body;

  try {
    const session = await stripe.checkout.sessions.retrieve(sessionId);

    if (session.payment_status !== "paid") {
      return res.status(400).json({ success: false, message: "Payment not completed." });
    }

    const { teacherId, studentId, duration, date, time } = session.metadata;

    const { Booking } = await import("../models/Booking.js");
    const { Teacher } = await import("../models/Teacher.js");
    const { createZoomMeeting } = await import("../middlewares/zoom.js");

    // ✅ Check 1: Same stripeSessionId — page refresh se double booking nahi hogi
    const existingBySession = await Booking.findOne({ stripeSessionId: sessionId });
    if (existingBySession) {
      console.log("⚠️ Already booked for session:", sessionId);
      return res.status(200).json({ success: true, data: existingBySession, message: "Already booked." });
    }

    // ✅ Check 2: Same teacher + date + time — duplicate slot nahi hoga
    const [year, month, day] = date.split("-").map(Number);
    const startOfDay = new Date(Date.UTC(year, month - 1, day, 0, 0, 0, 0));
    const endOfDay   = new Date(Date.UTC(year, month - 1, day, 23, 59, 59, 999));

    const existingSlot = await Booking.findOne({
      teacherId,
      date: { $gte: startOfDay, $lte: endOfDay },
      time,
      status: { $in: ["confirmed", "pending"] },
    });

    if (existingSlot) {
      return res.status(200).json({ success: true, data: existingSlot, message: "Already booked." });
    }

    // ✅ Create Zoom meeting ONCE
    const teacher = await Teacher.findById(teacherId).populate("userId", "email name");

    const zoomMeeting = await createZoomMeeting({
      topic: `Music Lesson with ${teacher.userId.name}`,
      startTime: new Date(`${date}T${time}:00`).toISOString(),
      duration: parseInt(duration),
      email: "me",
    });

    // ✅ Save booking WITH stripeSessionId
    const booking = await Booking.create({
      studentId: studentId || req.user._id,
      teacherId,
      date: new Date(date),
      time,
      duration: parseInt(duration),
      zoomMeetingId:   zoomMeeting.id,
      zoomJoinUrl:     zoomMeeting.join_url,
      zoomStartUrl:    zoomMeeting.start_url,
      status:          "confirmed",
      stripeSessionId: sessionId, // ✅ KEY — double booking rokta hai
    });

    console.log("✅ Booking created:", booking._id, "Session:", sessionId);
    res.status(201).json({ success: true, data: booking });

  } catch (err) {
    console.error("❌ verify-lesson-payment error:", err.message);
    res.status(500).json({ success: false, message: err.message });
  }
});

// ✅ My Subscription
router.get("/my-subscription", authPayment, async (req, res) => {
  try {
    const subscription = await Subscription.findOne({
      user: req.user._id,
      paymentStatus: "paid",
    }).sort({ purchasedAt: -1 });

    if (!subscription) return res.json({ hasSubscription: false });

    const isExpired = new Date() > new Date(subscription.expiresAt);

    res.json({
      hasSubscription: true,
      planType: subscription.subscription.name,
      price: subscription.price,
      isActive: !isExpired,
      expiryDate: subscription.expiresAt,
      purchasedAt: subscription.purchasedAt,
      status: isExpired ? "Expired" : "Active",
    });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

export default router;