import { NextRequest, 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(req: NextRequest) {
  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 { priceId } = await req.json();
    if (!priceId) return NextResponse.json({ error: 'Missing priceId' }, { status: 400 });

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

    if (!customerId) {
      const customer = await stripe.customers.create({
        email: user.email,
        metadata: { supabase_user_id: user.id },
      });
      customerId = customer.id;
      await sql`
        INSERT INTO user_subscriptions (user_id, stripe_customer_id, plan, status)
        VALUES (${user.id}, ${customerId}, 'free', 'active')
        ON CONFLICT (user_id) DO UPDATE SET stripe_customer_id = EXCLUDED.stripe_customer_id
      `;
    }

    const session = await stripe.checkout.sessions.create({
      customer: customerId,
      mode: 'subscription',
      line_items: [{ price: priceId, quantity: 1 }],
      success_url: `${process.env.NEXT_PUBLIC_APP_URL}/settings/billing?success=1`,
      cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}/settings/billing?canceled=1`,
      metadata: { user_id: user.id },
    });

    return NextResponse.json({ url: session.url });
  } catch (err: unknown) {
    logApiError('Stripe checkout 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 });
  }
}
