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';
import { resolveRequestOrigin } from '@server/lib/request-origin';

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 origin = resolveRequestOrigin(req);
    const portalSession = await stripe.billingPortal.sessions.create({
      customer: sub.stripeCustomerId,
      return_url: `${origin}/billing`,
    });

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