import type Stripe from 'stripe';

import { handleCustomerEvent } from './customer';
import { handleInvoiceEvent } from './invoice';
import { handlePaymentIntentEvent } from './payment-intent';
import { handleSetupIntentEvent } from './setup-intent';
import { handleSubscriptionEvent } from './subscription';

export default async function handleStripeEvent(event: any, client: Stripe) {
  switch (event.type) {
    case 'payment_intent.canceled':
    case 'payment_intent.created':
    case 'payment_intent.partially_funded':
    case 'payment_intent.payment_failed':
    case 'payment_intent.processing':
    case 'payment_intent.requires_action':
    case 'payment_intent.succeeded': {
      if (event.data?.object?.id) {
        const record = await client.paymentIntents.retrieve(event.data.object.id);
        event.data.object = {
          ...event.data.object,
          ...record,
        };
      }
      return handlePaymentIntentEvent(event, client);
    }

    // case 'setup_intent.created':
    case 'setup_intent.canceled':
    case 'setup_intent.requires_action':
    case 'setup_intent.setup_failed':
    case 'setup_intent.succeeded':
      return handleSetupIntentEvent(event, client);

    case 'customer.subscription.deleted':
    case 'customer.subscription.paused':
    case 'customer.subscription.pending_update_applied':
    case 'customer.subscription.pending_update_expired':
    case 'customer.subscription.resumed':
    case 'customer.subscription.trial_will_end':
    case 'customer.subscription.updated':
      return handleSubscriptionEvent(event, client);

    case 'customer.updated':
      return handleCustomerEvent(event);

    case 'invoice.created':
    case 'invoice.deleted':
    case 'invoice.finalization_failed':
    case 'invoice.finalized':
    case 'invoice.marked_uncollectible':
    case 'invoice.paid':
    case 'invoice.payment_action_required':
    case 'invoice.payment_failed':
    case 'invoice.payment_succeeded':
    case 'invoice.sent':
    case 'invoice.upcoming':
    case 'invoice.updated':
    case 'invoice.voided':
      return handleInvoiceEvent(event, client);

    default:
      return Promise.resolve(true);
  }
}
