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';

// --- ASA GENERATED START ---
// Route handler for billing/cancel slice.
// Cancels subscription at period end (not immediately).
// Security: requires authenticated user, validates subscription ownership.
// --- ASA GENERATED END ---

// --- USER CODE START ---

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

    const supabase = createAdminClient();

    const { data: subscription } = await supabase
      .from('subscriptions')
      .select('stripe_subscription_id, status')
      .eq('user_id', user!.id)
      .single();

    if (!subscription?.stripe_subscription_id) {
      return NextResponse.json(
        { success: false, error: 'No active subscription found' },
        { status: 404 },
      );
    }

    // Cancel at period end — user keeps access until billing period ends
    await stripe.subscriptions.update(subscription.stripe_subscription_id, {
      cancel_at_period_end: true,
    });

    // Update local status
    await supabase
      .from('subscriptions')
      .update({ status: 'canceling' })
      .eq('user_id', user!.id);

    return NextResponse.json({ success: true, error: null });
  } catch (err) {
    console.error('[billing/cancel] Error:', err);
    return NextResponse.json(
      { success: false, error: 'Failed to cancel subscription' },
      { status: 500 },
    );
  }
}

// --- USER CODE END ---
