import { NextRequest, NextResponse } from "next/server";
import Stripe from "stripe";

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

export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const sessionId = searchParams.get("session_id");

    if (!sessionId) {
      return NextResponse.json(
        { error: "Session ID is required" },
        { status: 400 }
      );
    }

    // Retrieve the session with expanded payment_intent, line_items, and discounts
    const session = await stripe.checkout.sessions.retrieve(sessionId, {
      expand: [
        "line_items",
        "total_details",
        "total_details.breakdown.discounts",
      ],
    });

    // Calculate discount information
    const amountTotal = session.amount_total || 0; // Final amount in cents
    const amountSubtotal = session.amount_subtotal || 0; // Original amount in cents
    const stripeTotalDiscountCents =
      session.total_details?.amount_discount || 0; // Stripe discount in cents

    // Get wallet discount from metadata (applied before Stripe checkout)
    const walletDiscount = session.metadata?.discount_applied
      ? parseFloat(session.metadata.discount_applied)
      : 0;
    const walletBalance = session.metadata?.wallet_balance
      ? parseFloat(session.metadata.wallet_balance)
      : 0;
    const originalAmount = session.metadata?.original_amount
      ? parseFloat(session.metadata.original_amount)
      : amountSubtotal / 100;

    // Get Stripe promo code discount if applied
    let couponCode = null;
    let discountPercentage = null;
    let stripeDiscountAmount = 0;

    if (
      session.total_details?.breakdown?.discounts &&
      session.total_details.breakdown.discounts.length > 0
    ) {
      const discount = session.total_details.breakdown.discounts[0];

      // Access the discount object directly (it's expanded)
      if (discount.discount && typeof discount.discount === "object") {
        const discountObj = discount.discount as any;
        if (discountObj.coupon) {
          couponCode = discountObj.coupon.id;
          if (discountObj.coupon.percent_off) {
            discountPercentage = discountObj.coupon.percent_off;
          }
          if (discountObj.coupon.amount_off) {
            stripeDiscountAmount = discountObj.coupon.amount_off / 100; // Convert to euros
          }
        }
      }

      // Fallback to discount amount if we couldn't get the coupon details
      if (!stripeDiscountAmount && !discountPercentage) {
        stripeDiscountAmount = discount.amount / 100; // Convert to euros
      }
    }

    // Calculate final amount: original - wallet discount - Stripe promo discount
    // Note: Stripe already applies promo discount, so amountTotal is after both discounts
    const finalAmount = amountTotal / 100; // Final amount after all discounts
    const totalDiscount = walletDiscount + stripeDiscountAmount; // Total discount (wallet + promo code)

    return NextResponse.json({
      sessionId: session.id,
      paymentStatus: session.payment_status,
      amount: originalAmount, // Original amount in euros (before any discounts)
      discount: totalDiscount, // Total discount (wallet + promo code)
      walletDiscount: walletDiscount, // Wallet discount in euros
      stripeDiscount: stripeDiscountAmount, // Stripe promo code discount in euros
      walletBalance: walletBalance, // User wallet balance at time of payment
      finalAmount: finalAmount, // Final amount in euros (after all discounts)
      couponCode: couponCode, // Stripe coupon code if applied
      discountPercentage: discountPercentage, // Percentage discount if applicable
      currency: session.currency,
      metadata: session.metadata,
    });
  } catch (error: any) {
    console.error("Error retrieving session details:", error);
    return NextResponse.json(
      { error: error.message || "Failed to retrieve session details" },
      { status: 500 }
    );
  }
}
