import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { getStripeClientFromDb } from '@server/lib/stripe';
import { db, subscriptions } from '@server/db/drizzle';
import { eq, desc } from 'drizzle-orm';
import { initDatabase } from '@server/db/init';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    await initDatabase();
    const restaurantId = req.session.restaurantId!;

    const rows = await db.select({ stripeCustomerId: subscriptions.stripeCustomerId })
      .from(subscriptions)
      .where(eq(subscriptions.restaurantId, restaurantId))
      .orderBy(desc(subscriptions.createdAt))
      .limit(1);
    const sub = rows[0];

    if (!sub?.stripeCustomerId) {
      return NextResponse.json({ paymentMethod: null });
    }

    const stripe = await getStripeClientFromDb();
    const customer = await stripe.customers.retrieve(sub.stripeCustomerId, {
      expand: ['invoice_settings.default_payment_method'],
    });

    if (customer.deleted) {
      return NextResponse.json({ paymentMethod: null });
    }

    const pm = customer.invoice_settings?.default_payment_method;
    if (!pm || typeof pm === 'string') {
      const methods = await stripe.paymentMethods.list({ customer: sub.stripeCustomerId, type: 'card', limit: 1 });
      const card = methods.data[0];
      if (!card) return NextResponse.json({ paymentMethod: null });

      return NextResponse.json({
        paymentMethod: {
          id: card.id,
          brand: card.card?.brand ?? 'unknown',
          last4: card.card?.last4 ?? '****',
          expMonth: card.card?.exp_month ?? 0,
          expYear: card.card?.exp_year ?? 0,
        },
      });
    }

    const card = typeof pm === 'string' ? null : pm;
    if (!card || !card.card) return NextResponse.json({ paymentMethod: null });

    return NextResponse.json({
      paymentMethod: {
        id: card.id,
        brand: card.card.brand,
        last4: card.card.last4,
        expMonth: card.card.exp_month,
        expYear: card.card.exp_year,
      },
    });
  })
);
