import { NextRequest, NextResponse } from "next/server";
import Stripe from "stripe";
import {
  validateAmount,
  fetchWalletBalance,
  calculateDiscount,
  createLineItems,
  createSessionMetadata,
  createCheckoutSession,
  type CreateIntentParams,
} from "./helpers-create-intent";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || "", {
  apiVersion: "2025-10-29.clover",
});

export async function POST(request: NextRequest) {
  try {
    // Extract request data
    const {
      stripe_customer_id,
      amount,
      metadata,
      successUrl,
      cancelUrl,
      selectedEvents,
      customerEmail,
      token,
    }: CreateIntentParams = await request.json();

    console.log("customer email : ", customerEmail);

    // Validate amount
    const validation = validateAmount(amount);
    if (!validation.valid) {
      return NextResponse.json({ error: validation.error }, { status: 400 });
    }

    // Fetch user wallet balance for discount
    let walletBalance = 0;
    let walletData = null;
    if (metadata?.user_id && token) {
      const apiUrl =
        process.env.NEXT_PUBLIC_API_URL_New ||
        "https://backendv2testing.eventx.fr";
      const walletResult = await fetchWalletBalance(
        metadata.user_id,
        token,
        apiUrl
      );
      walletBalance = walletResult.walletBalance;
      walletData = walletResult.walletData;
    }

    // Calculate total amount, discount, and final amount
    const { totalAmount, discountAmount, finalAmount } = calculateDiscount(
      selectedEvents,
      walletBalance
    );

    // Create line items with adjusted prices (discount already applied)
    const lineItems = createLineItems(
      selectedEvents,
      totalAmount,
      discountAmount
    );

    // Create session metadata
    const sessionMetadata = createSessionMetadata(
      metadata,
      walletBalance,
      discountAmount,
      totalAmount,
      finalAmount
    );

    // Get origin for success/cancel URLs
    const origin = request.headers.get("origin") || "";

    // Create Stripe checkout session
    const session = await createCheckoutSession(
      stripe,
      lineItems,
      sessionMetadata,
      origin,
      customerEmail,
      discountAmount
    );

    // Return response with session details
    return NextResponse.json({
      sessionId: session.id,
      url: session.url,
      walletBalance: walletBalance,
      discountApplied: discountAmount,
      originalAmount: totalAmount,
      finalAmount: finalAmount,
      walletData: walletData,
    });
  } catch (error: any) {
    console.error("Error creating checkout session:", error);
    return NextResponse.json(
      { error: error.message || "Failed to create checkout session" },
      { status: 500 }
    );
  }
}
