import Stripe from 'stripe';
import dotenv from 'dotenv';
dotenv.config();

const stripe = new Stripe(process.env.STRIPE_SECRET);

export default class PaymentsHandler {

    static async finishConnectSetup(req, res) {
        const { code, networkId } = req.body;
        console.log("onboarded", networkId)

        const response = await stripe.oauth.token({
            grant_type: "authorization_code",
            code,
        });

        const { stripe_user_id, access_token } = response;

        await db.networks.update(
            networkId,
            {
                stripeAccountId: stripe_user_id,
                stripeAccessToken: access_token, // rarely used, long-term access token for the platform
            }
        );

        res.json({ success: true });
    }

    static async getProfile(networkId) {
        let network = global.db.networks.get(networkId)
        if (network) {
            if (network.stripeAccountId) {
                const account = await stripe.accounts.retrieve(network.stripeAccountId);
                return {
                    chargesEnabled: account.charges_enabled,
                    payoutsEnabled: account.payouts_enabled,
                    detailsSubmitted: account.details_submitted,
                    email: account.email,
                    country: account.country,
                }
            } else {
                return { connected: false }
            }
        } else {
            throw new Error(`Network ${networkId} not found`)
        }
    }

    static async getCustomers() {
        const customers = await stripe.customers.list(
            { limit: 100 },
            { stripeAccount: 'acct_connected_account_id' }
        );
        console.log(customers)
    }

    static async newSubscription(req, res) {
        try {
            const session = await stripe.checkout.sessions.create({
                mode: "payment",
                payment_method_types: ["card"],
                metadata: {
                    productId: "50_month_sub"
                },
                line_items: [
                    {
                        price_data: {
                            currency: "usd",
                            product_data: {
                                name: "Monthly Subscription"
                            },
                            unit_amount: 5000
                        },
                        quantity: 1
                    }
                ],
                success_url: `${process.env.PROTOCOL + process.env.BASE_URL}/success`,
                cancel_url: `${process.env.PROTOCOL + process.env.BASE_URL}/events`
            });

            res.json({ url: session.url });
        } catch (err) {
            console.error(err);
            res.status(500).json({ error: "Something went wrong." });
        }
    }

    static webhook = (req, res) => {
        const sig = req.headers["stripe-signature"];

        try {
            const event = stripe.webhooks.constructEvent(
                req.body,
                sig,
                process.env.WEBHOOK_SECRET
            );

            if (event.type === "checkout.session.completed") {
                const session = event.data.object;
                let toStore = {
                    "product": session.metadata.productId,
                    "email": session.customer_details.email,
                    "name": session.customer_details.name,
                    "time": global.currentTime(),
                    "amount": session.amount_total,
                }
                global.db.payments.add(toStore)
            }

            res.sendStatus(200);
        } catch (err) {
            console.error(err);
            res.sendStatus(400);
        }
    }
}