import fp from 'fastify-plugin';
import Stripe from 'stripe';
import type { FastifyInstance } from 'fastify';

export default fp(async function stripePlugin(fastify: FastifyInstance) {
  const key = process.env.STRIPE_SECRET_KEY;
  if (!key) {
    fastify.log.warn('STRIPE_SECRET_KEY non définie — le plugin Stripe est désactivé');
    return;
  }

  const stripe = new Stripe(key, {
    apiVersion: (process.env.STRIPE_API_VERSION as Stripe.StripeConfig['apiVersion']) ?? '2023-10-16',
  });

  fastify.decorate('stripe', stripe);

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

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