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({ invoices: [] });
    }

    const stripe = await getStripeClientFromDb();
    const invoices = await stripe.invoices.list({
      customer: sub.stripeCustomerId,
      limit: 24,
    });

    const normalized = invoices.data.map(inv => ({
      id: inv.id,
      number: inv.number,
      status: inv.status,
      amount: (inv.status === 'paid' ? inv.amount_paid : inv.amount_due) / 100,
      currency: inv.currency.toUpperCase(),
      periodStart: new Date(inv.period_start * 1000).toISOString(),
      periodEnd: new Date(inv.period_end * 1000).toISOString(),
      createdAt: new Date(inv.created * 1000).toISOString(),
      pdfUrl: inv.invoice_pdf,
      hostedUrl: inv.hosted_invoice_url,
    }));

    return NextResponse.json({ invoices: normalized });
  })
);
