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

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,
      customerEmail,
      token,
      duration,
      categoryName,
    }: CreateCategoryIntentParams & {
      duration?: number;
      categoryName?: string;
    } = await request.json();

    console.log("Category payment intent - customer email:", customerEmail);
    console.log("Category payment intent - amount:", amount);
    console.log("Category payment intent - metadata:", metadata);
    console.log("Category payment intent - successUrl:", successUrl);
    console.log("Category payment intent - cancelUrl:", cancelUrl);
    console.log("Category payment intent - duration:", duration);
    console.log("Category payment intent - categoryName:", categoryName);

    // 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(
      amount,
      walletBalance
    );

    console.log("Category payment intent - totalAmount:", totalAmount);
    console.log("Category payment intent - discountAmount:", discountAmount);
    console.log("Category payment intent - finalAmount:", finalAmount);

    // Create line items
    const lineItems = createLineItems(totalAmount, duration || 7, categoryName);

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

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

    console.log("Category payment intent - lineItems:", lineItems);
    console.log("Category payment intent - sessionMetadata:", sessionMetadata);
    console.log("Category payment intent - origin:", origin);
    console.log("Category payment intent - customerEmail:", customerEmail);
    console.log("Category payment intent - discountAmount:", discountAmount);
    console.log("Category payment intent - successUrl:", successUrl);
    console.log("Category payment intent - cancelUrl:", cancelUrl);

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

    // 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 category checkout session:", error);
    return NextResponse.json(
      { error: error.message || "Failed to create checkout session" },
      { status: 500 }
    );
  }
}
