const fp = require('fastify-plugin');
const Stripe = require('stripe');

module.exports = fp(async function (fastify, opts) {
  const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

  fastify.decorate('stripe', stripe);

  fastify.decorate('createCustomer', async (email, name) => {
    return stripe.customers.create({
      email,
      name
    });
  });

  fastify.decorate('createSubscription', async (customerId, priceId) => {
    return stripe.subscriptions.create({
      customer: customerId,
      items: [{ price: priceId }],
      payment_behavior: 'default_incomplete',
      expand: ['latest_invoice.payment_intent'],
    });
  });
});