import { stripe } from './stripe';
import Stripe from 'stripe';

export async function constructWebhookEvent(
  body: string | Buffer,
  signature: string
): Promise<Stripe.Event> {
  const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;

  if (!webhookSecret) {
    throw new Error('Missing STRIPE_WEBHOOK_SECRET');
  }

  try {
    return stripe.webhooks.constructEvent(body, signature, webhookSecret);
  } catch (err) {
    throw new Error(`Webhook Error: ${(err as Error).message}`);
  }
}

export type WebhookHandler = (event: Stripe.Event) => Promise<void>;

export const webhookHandlers: Record<string, WebhookHandler> = {
  'checkout.session.completed': async (event) => {
    const session = event.data.object as Stripe.Checkout.Session;
    const userId = session.metadata?.userId;

    // Stripe requires amount in cents, convert for display
    const amount = session.amount_total ? session.amount_total / 100 : 0;

    console.log(
      `Payment successful for user ${userId}, amount: $${amount}`
    );

    // TODO: Update user subscription in database
  },

  'customer.subscription.created': async (event) => {
    const subscription = event.data.object as Stripe.Subscription;
    const customerId = subscription.customer as string;

    console.log(`Subscription created for customer ${customerId}`);

    // TODO: Update user subscription status
  },

  'customer.subscription.updated': async (event) => {
    const subscription = event.data.object as Stripe.Subscription;
    const customerId = subscription.customer as string;

    console.log(
      `Subscription updated for customer ${customerId}, status: ${subscription.status}`
    );

    // TODO: Update subscription status in database
  },

  'customer.subscription.deleted': async (event) => {
    const subscription = event.data.object as Stripe.Subscription;
    const customerId = subscription.customer as string;

    console.log(`Subscription cancelled for customer ${customerId}`);

    // TODO: Handle subscription cancellation
  },

  'invoice.payment_failed': async (event) => {
    const invoice = event.data.object as Stripe.Invoice;
    const customerId = invoice.customer as string;

    console.log(`Payment failed for customer ${customerId}`);

    // TODO: Send payment failure notification
  },
};

export async function handleWebhook(event: Stripe.Event): Promise<void> {
  const handler = webhookHandlers[event.type];

  if (handler) {
    await handler(event);
  } else {
    console.log(`Unhandled event type: ${event.type}`);
  }
}
