import { NextRequest, NextResponse } from 'next/server';
import { requireAuth } from '@/shared/auth/guards';
import { stripe } from '@/shared/billing/stripe-client';
import { createAdminClient } from '@/shared/db/supabase-client';
import { subscribeInputSchema } from './schemas';
import type { SubscribeOutput } from './schemas';

// --- ASA GENERATED START ---
// Route handler for billing/subscribe slice.
// Creates Stripe Checkout Session for subscription upgrade.
// Security: requires authenticated user, creates Stripe Customer if needed.
// --- ASA GENERATED END ---

// --- USER CODE START ---

export async function POST(request: NextRequest): Promise<NextResponse<SubscribeOutput>> {
  try {
    const { user, response } = await requireAuth(request);
    if (response) return response as NextResponse<SubscribeOutput>;

    const body = await request.json();
    const parsed = subscribeInputSchema.safeParse(body);

    if (!parsed.success) {
      return NextResponse.json(
        { checkout_url: null, error: parsed.error.errors[0]?.message ?? 'Invalid input' },
        { status: 400 },
      );
    }

    const { price_id } = parsed.data;
    const supabase = createAdminClient();

    // Get or create Stripe customer
    const { data: subscription } = await supabase
      .from('subscriptions')
      .select('stripe_customer_id')
      .eq('user_id', user!.id)
      .single();

    let customerId = subscription?.stripe_customer_id;

    if (!customerId) {
      const customer = await stripe.customers.create({
        email: user!.email,
        metadata: { supabase_user_id: user!.id },
      });
      customerId = customer.id;

      // Upsert subscription record with customer ID
      await supabase.from('subscriptions').upsert({
        user_id: user!.id,
        stripe_customer_id: customerId,
        plan: 'free',
        status: 'active',
      }, { onConflict: 'user_id' });
    }

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

    return NextResponse.json({ checkout_url: session.url, error: null });
  } catch (err) {
    console.error('[billing/subscribe] Error:', err);
    return NextResponse.json(
      { checkout_url: null, error: 'Failed to create checkout session' },
      { status: 500 },
    );
  }
}

// --- USER CODE END ---
