import { NextResponse } from 'next/server';
import { createStripeClient } from '@/lib/stripe/server';
import { createClient } from '@/lib/supabase/server';
import { sql } from '@/lib/db/postgres';
import { logApiError } from '@/lib/api/security';

export async function POST() {
  try {
    const stripe = createStripeClient();
    const supabase = await createClient();
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const { rows } = await sql<{ stripe_customer_id: string | null }>`
      SELECT stripe_customer_id FROM user_subscriptions WHERE user_id = ${user.id} LIMIT 1
    `;
    const customerId = rows[0]?.stripe_customer_id ?? null;

    if (!customerId) {
      return NextResponse.json({ error: 'No billing account' }, { status: 400 });
    }

    const session = await stripe.billingPortal.sessions.create({
      customer: customerId,
      return_url: `${process.env.NEXT_PUBLIC_APP_URL}/settings/billing`,
    });

    return NextResponse.json({ url: session.url });
  } catch (err: unknown) {
    logApiError('Stripe portal POST error', err);
    const msg = err instanceof Error ? err.message : 'Unknown error';
    return NextResponse.json({ error: msg }, { status: msg === 'Stripe is not configured' ? 503 : 500 });
  }
}
