const Stripe = require("stripe");
const userModel = require("../models/user");
const discussionFormModel = require("../models/discussionForm");
const requestFormModel = require("../models/requestForm");
const { default: mongoose } = require("mongoose");
require("dotenv").config();

const stripe = Stripe(process.env.STRIPE_SECRET_KEY);

const createSetupIntent = async (req, res) => {
    try {
        const _id = req.user._id

        let user = await userModel.findOne({ _id });

        if (!user) return res.status(400).json({ success: false, msg: 'User not found' })

        if (!user.stripeCustomerId) {
            const customer = await stripe.customers.create({
                name: user.fullName,
                email: user.email,
            });
            user.stripeCustomerId = customer.id;
            await user.save({ validateBeforeSave: false });
        }

        const setupIntent = await stripe.setupIntents.create({
            customer: user.stripeCustomerId,
            payment_method_types: ["card"],
        });

        return res.json({
            success: true, customerId: user.stripeCustomerId, clientSecret: setupIntent.client_secret,
        });
    } catch (error) {
        return res.status(403).json({
            success: false, msg: "Something Went Wrong!", error: error.message
        })
    }
}

const savePaymentMethod = async (req, res) => {
    try {
        const { customerId, paymentMethodId } = req.body;

        await stripe.paymentMethods.attach(paymentMethodId, {
            customer: customerId,
        });

        await stripe.customers.update(customerId, {
            invoice_settings: { default_payment_method: paymentMethodId },
        });

        return res.json({
            success: true, message: "Card saved successfully", paymentMethodId,
        });
    } catch (error) {
        return res.status(403).json({
            success: false, msg: "Something Went Wrong!", error: error.message
        })
    }
}

const createPayment = async (req, res) => {
    try {
        const { customerId, amount, paymentMethodId, formId, formType } = req.body;

        if (formType !== "discussion" && formType !== "request") {
            return res.status(400).json({
                success: false, msg: "Invalid form type. Must be 'discussion' or 'request'."
            });
        }

        if (!formId) return res.status(400).json({ success: false, msg: "formId is required!" });
        if (!mongoose.Types.ObjectId.isValid(formId)) return res.status(400).json({ success: false, msg: "Invalid formId provided!" });



        const paymentIntent = await stripe.paymentIntents.create({
            amount: amount * 100, // rupees → paisa
            currency: "usd",
            customer: customerId,
            payment_method: paymentMethodId,
            off_session: true,
            confirm: true,
        });
        if (paymentIntent.status === "succeeded") {
            if (formType === "discussion") {
                await discussionFormModel.findByIdAndUpdate(formId, { status: "Paid" });
            }
            if (formType === "request") {
                await requestFormModel.findByIdAndUpdate(formId, { status: "Paid" });
            }
            return res.json({ success: true, paymentIntent, msg: "Payment successful!" });
        }
        return res.status(400).json({ success: false, msg: "Payment failed!", paymentIntent });
    } catch (error) {
        return res.status(403).json({
            success: false, msg: "Something Went Wrong!", error: error.message
        })
    }
}

const getSavedCards = async (req, res) => {
    try {
        const _id = req.user._id

        const user = await userModel.findOne({ _id });
        if (!user || !user.stripeCustomerId) {
            return res.status(404).json({ success: false, msg: "User not found or no Stripe customer" });
        }

        // List all cards for this customer
        const paymentMethods = await stripe.paymentMethods.list({
            customer: user.stripeCustomerId,
            type: "card",
        });

        // cards
        // id → Use this paymentMethodId for payments.

        res.json({
            success: true,
            cards: paymentMethods.data
        });
    } catch (error) {
        res.status(500).json({ success: false, msg: "Something went wrong", error: error.message });
    }
};


module.exports = {
    createSetupIntent, savePaymentMethod, createPayment, getSavedCards
}