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 POST = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    await initDatabase();
    const stripe = await getStripeClientFromDb();
    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(
        { error: 'No Stripe customer found. Please subscribe to a plan first.', code: 'NO_CUSTOMER' },
        { status: 400 }
      );
    }

    const rawHost = req.headers.get('host');
    const origin =
      process.env.NEXT_PUBLIC_APP_URL ??
      (process.env.VERCEL_URL ? `https://${process.env.VERCEL_URL}` : null) ??
      req.headers.get('origin') ??
      (rawHost ? `https://${rawHost}` : null);
    const portalSession = await stripe.billingPortal.sessions.create({
      customer: sub.stripeCustomerId,
      return_url: `${origin}/billing`,
    });

    return NextResponse.json({ url: portalSession.url });
  })
);
