/**
 * Stripe Session Retrieval Endpoint
 *
 * Retrieves Stripe checkout session details for email prefill and verification flow.
 *
 * Security features:
 * - Session ID validation
 * - Error handling
 */

import { NextRequest, NextResponse } from "next/server";
import { stripe } from "@/lib/stripe";
import { logger } from "@/lib/logger";

// Force dynamic rendering
export const dynamic = "force-dynamic";
export const runtime = "nodejs";

export async function GET(
  request: NextRequest,
  { params }: { params: { sessionId: string } },
) {
  try {
    const { sessionId } = params;

    // Validate session ID format
    if (!sessionId || !sessionId.startsWith("cs_")) {
      return NextResponse.json(
        { error: "Invalid session ID format" },
        { status: 400 },
      );
    }

    // Retrieve session from Stripe
    const session = await stripe.checkout.sessions.retrieve(sessionId);

    // Return relevant session details (no sensitive payment info)
    return NextResponse.json({
      id: session.id,
      customer_details: {
        email: session.customer_details?.email,
        name: session.customer_details?.name,
      },
      metadata: session.metadata,
      payment_status: session.payment_status,
      status: session.status,
    });
  } catch (error) {
    logger.error("Stripe session retrieval error", error);

    // Check if session not found
    if (
      error instanceof Error &&
      error.message.includes("No such checkout.session")
    ) {
      return NextResponse.json({ error: "Session not found" }, { status: 404 });
    }

    return NextResponse.json(
      { error: "Failed to retrieve session" },
      { status: 500 },
    );
  }
}
