require('dotenv').config()
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY)
exports.subscribeUser = async (req, res) => {
    console.log("respoce of subscribeUser", req.query);

    var { plan, userId } = req.query;

    console.log("Query parameters plan:", plan);
    console.log("Query parameters userid:", userId);
    
    if (!userId) {
        return res.status(400).send('Subscription plan not found');
    }

    let priceId;
    //   plan ='starter';
    console.log("plan selected:", plan);

    // Map subscription plan to priceId
    switch (plan.toLowerCase()) {
        case 'basic':
            priceId = 'price_1QWjfdA1klF7MT0HjYz72jAO';
            break;

        case 'standard':
            priceId = 'price_1QWjg8A1klF7MT0H8THzQG0n';
            break;
        case 'premium':
            priceId = 'price_1QWjgQA1klF7MT0HfdKVOggd';
            break;
        case 'starter':
            priceId = 'price_1QVExiA1klF7MT0HJ2fWbN4U';
            break;
        case 'business':
            priceId = 'price_1QWkBDA1klF7MT0HDhGKZpbN';
            break;
        case 'enterprise':
            priceId = 'price_1QWkBVA1klF7MT0HeigQVQBh';
            break;
        case 'corporate':
            priceId = 'price_1QWkBxA1klF7MT0Hb0kWj3b9';
            break;

        default:
            return res.status(400).send('Subscription plan not found');
    }

    try {
        // Create a checkout session
        const session = await stripe.checkout.sessions.create({
            mode: 'subscription',
            line_items: [
                {
                    price: priceId,
                    quantity: 1,
                }
            ],
            success_url: `${process.env.BASE_URL}/Success`,
            cancel_url: `${process.env.BASE_URL}/cancel`,
            metadata: {
                userId,
                plan// Attach the userId in metadata
            },
        });
        console.log("redirect url", session.url);

        // res.redirect(session.url); // Redirect to Stripe Checkout
        res.json({ url: session.url });
    } catch (error) {
        console.error("Error creating checkout session:", error);
        res.status(500).send('Internal server error');
    }
};



// module.exports = subscribeUser;