import { NextRequest, NextResponse } from 'next/server';
import { getUserFromRequest, jsonError } from '@/lib/auth-helpers';

export const dynamic = 'force-dynamic';

const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3000';
const VALID_TIERS = new Set(['analyst', 'desk']);

/**
 * Checkout proxy — Next.js → Express → Stripe.
 *
 * Session 8 cutover: previously this route created NexaPay payment
 * links; now it forwards to the Express `/api/stripe/checkout` route
 * (Session 3.4 + 7i) which creates a Stripe Checkout Session
 * server-side. The browser never sees `sk_test_*` / `sk_live_*` —
 * only the resulting `https://checkout.stripe.com/...` redirect URL.
 *
 * Response shape — preserves the existing `{ url }` field so older
 * Pricing CTA code that read `.url` keeps working. Express returns
 * `{ checkout_url, session_id }`; we rename and forward both so
 * either field name resolves on the client.
 */
async function handle(req: NextRequest) {
  const user = await getUserFromRequest(req);
  if (!user) return jsonError(401, 'Log in to upgrade.');

  // Tier resolution — query string for GET (button hrefs), body for POST.
  let tier: string | null = null;
  let founderCode: string | undefined;
  const url = new URL(req.url);
  const queryTier = url.searchParams.get('tier');
  if (queryTier) tier = queryTier;
  if (req.method === 'POST') {
    try {
      const body = (await req.json().catch(() => ({}))) as { tier?: string; founder_code?: string };
      if (body.tier) tier = body.tier;
      if (body.founder_code) founderCode = body.founder_code;
    } catch {
      /* tier may still be on the query string */
    }
  }
  if (!tier || !VALID_TIERS.has(tier)) {
    return jsonError(400, 'Pick a valid tier (analyst or desk).');
  }

  // Forward to Express. The bearer token from the browser is the same
  // one Express's requireAuth verifies — no token rewriting on this hop.
  const authHeader = req.headers.get('authorization');
  if (!authHeader) return jsonError(401, 'Log in to upgrade.');

  try {
    const upstream = await fetch(`${BACKEND_URL}/api/stripe/checkout`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: authHeader,
      },
      body: JSON.stringify({ tier, ...(founderCode ? { founder_code: founderCode } : {}) }),
    });

    const data = (await upstream.json().catch(() => ({}))) as {
      checkout_url?: string;
      session_id?: string;
      error?: string;
    };

    if (!upstream.ok) {
      return NextResponse.json(
        { error: data.error || 'Checkout creation failed. Try again in a moment.' },
        { status: upstream.status },
      );
    }

    const checkoutUrl = data.checkout_url;
    if (!checkoutUrl) {
      // Defensive: Express returned 200 with no URL — should never happen,
      // but if it does we don't want to silently redirect to undefined.
      return jsonError(502, 'Checkout creation incomplete. Try again.');
    }

    // GET requests (used by legacy <a> hrefs) redirect directly so a
    // plain link click flows to Stripe without JS.
    if (req.method === 'GET') {
      return NextResponse.redirect(checkoutUrl, { status: 303 });
    }

    // POST returns JSON so the new Pricing onClick handler can navigate
    // explicitly (gives us a place to show loading state first).
    return NextResponse.json({
      url: checkoutUrl,
      checkout_url: checkoutUrl,
      session_id: data.session_id,
    });
  } catch {
    return jsonError(502, 'Payment processor is unreachable. Try again in a moment.');
  }
}

export async function GET(req: NextRequest)  { return handle(req); }
export async function POST(req: NextRequest) { return handle(req); }
