// import { Booking } from "../models/Booking.js";
// import { Payment } from "../models/Payment.js";
import Stripe from "stripe";
import { User } from "../models/usermodels";
import Subscription from "../models/Subscription.js";
const stripe = Stripe(process.env.STRIPE_SECRET_KEY);

export const createCheckoutSession = async (req, res) => {
  const { userId, type, name, price, duration, lessonsCount, minUser } =
    req.body;

  const user = await User.findById(userId);

  if (!user) return res.status(404).json({ error: "User or plan not found" });

  try {
    // 1. Create a subscription record with pending status
    const subscription = await Subscription.create({
      user: user._id,
      subscription: {
        name: name,
        durationMinutes: duration || 0,
        lessonCount: lessonsCount || 1,
        price: price,
        description: description || "",
        features: features || [],
        users: minUser || [],
      },
      price: price,
      paymentStatus: "pending",
    });

    // 2. Create Stripe checkout session
    const session = await stripe.checkout.sessions.create({
      payment_method_types: ["card"],
      line_items: [
        {
          price_data: {
            currency: "usd",
            product_data: { name: plan.name },
            unit_amount: plan.price * 100,
          },
          quantity: 1,
        },
      ],
      mode: "payment",
      success_url: `${process.env.FRONTEND_URL}/success?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${process.env.FRONTEND_URL}/cancel`,
      metadata: {
        subscriptionId: subscription._id.toString(),
        userId: user._id.toString(),
      },
    });

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

// controllers/paymentController.js
export const handleWebhook = async (req, res) => {
  const sig = req.headers["stripe-signature"];
  let event;

  try {
    event = stripe.webhooks.constructEvent(
      req.body,
      sig,
      process.env.STRIPE_WEBHOOK_SECRET,
    );
  } catch (err) {
    return res.status(400).send(`Webhook Error: ${err.message}`);
  }

  if (event.type === "checkout.session.completed") {
    const session = event.data.object;
    const subscriptionId = session.metadata.subscriptionId;

    const subscription = await Subscription.findById(subscriptionId);
    if (!subscription) return res.status(404).send("Subscription not found");

    subscription.paymentStatus = "paid";
    subscription.purchasedAt = new Date();

    if (
      subscription.subscription.durationMinutes &&
      subscription.subscription.durationMinutes > 0
    ) {
      subscription.expiresAt = new Date(
        Date.now() + subscription.subscription.durationMinutes * 60 * 1000,
      );
    }

    await subscription.save();
  }

  res.json({ received: true });
};
// export const createCheckoutSession = async (req, res) => {
//   try {
//     const { amount, userId, teacherId, date, time, duration, type } = req.body;

//     // 1️⃣ Create Booking FIRST (pending state)
//     const booking = await Booking.create({
//       studentId: userId,
//       teacherId,
//       date,
//       time,
//       duration,
//       status: "pending",
//     });

//     // 2️⃣ Create Stripe Session linked to booking
//     const session = await stripe.checkout.sessions.create({
//       payment_method_types: ["card"],
//       mode: "payment",
//       line_items: [
//         {
//           price_data: {
//             currency: "usd",
//             product_data: {
//               name: "Lesson Booking",
//             },
//             unit_amount: amount * 100,
//           },
//           quantity: 1,
//         },
//       ],

//       success_url: `${process.env.FRONTEND_URL}/success`,
//       cancel_url: `${process.env.FRONTEND_URL}/cancel`,

//       // 3️⃣ IMPORTANT: Link everything in metadata
//       metadata: {
//         userId,
//         teacherId,
//         bookingId: booking._id.toString(),
//         type,
//         amount,
//       },
//     });

//     // 4️⃣ Save Payment record (pending)
//     await Payment.create({
//       userId,
//       type,
//       amount,
//       stripeSessionId: session.id,
//       status: "pending",
//       bookingId: booking._id,
//     });

//     // 5️⃣ Return checkout URL
//     return res.status(200).json({
//       success: true,
//       url: session.url,
//       bookingId: booking._id,
//       sessionId: session.id,
//     });
//   } catch (error) {
//     console.error("Checkout Error:", error);
//     return res.status(500).json({
//       success: false,
//       message: "Failed to create booking & payment session",
//     });
//   }
// };
// export const stripeWebhook = async (req, res) => {
//   const sig = req.headers["stripe-signature"];

//   let event;

//   try {
//     event = stripe.webhooks.constructEvent(
//       req.body,
//       sig,
//       process.env.STRIPE_WEBHOOK_SECRET,
//     );
//   } catch (err) {
//     return res.status(400).send(`Webhook Error: ${err.message}`);
//   }

//   try {
//     if (event.type === "checkout.session.completed") {
//       const session = event.data.object;

//       const { userId, bookingId, type } = session.metadata;

//       // 1️⃣ Mark payment as PAID
//       await Payment.findOneAndUpdate(
//         { stripeSessionId: session.id },
//         { status: "paid" },
//       );

//       // 2️⃣ Activate booking
//       await Booking.findByIdAndUpdate(bookingId, {
//         status: "confirmed",
//       });
//     }

//     return res.json({ received: true });
//   } catch (error) {
//     console.error("Webhook Error:", error);
//     return res.status(500).json({ success: false });
//   }
// };
