/**
 * Stripe Checkout Session API
 * Creates a checkout session for swag store orders
 */

export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import { headers } from 'next/headers';
import prisma from '@/lib/db';
import { cookies } from 'next/headers';
import { initializeOrderExecution } from '@/lib/order-to-cash/orchestrator';
import { logAgentAction } from '@/lib/order-to-cash/agent-logger';

const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
const STRIPE_API_VERSION = '2024-12-18.acacia';

function generateOrderNumber() {
  const timestamp = Date.now().toString(36).toUpperCase();
  const random = Math.random().toString(36).slice(2, 6).toUpperCase();
  return `GFS-${timestamp}-${random}`;
}

export async function POST(request: NextRequest) {
  if (!STRIPE_SECRET_KEY) {
    return NextResponse.json(
      { error: 'Stripe is not configured. Please add STRIPE_SECRET_KEY to environment.' },
      { status: 500 }
    );
  }

  try {
    const { customerName, customerEmail, shippingAddress, billingAddress } = await request.json();
    const cookieStore = await cookies();
    const sessionId = cookieStore.get('swag_session')?.value;

    if (!sessionId) {
      return NextResponse.json({ error: 'No cart found' }, { status: 400 });
    }

    // Get cart
    const cart = await prisma.swagCart.findUnique({
      where: { sessionId },
      include: {
        items: {
          include: {
            variant: {
              include: { product: true },
            },
          },
        },
      },
    });

    if (!cart || cart.items.length === 0) {
      return NextResponse.json({ error: 'Cart is empty' }, { status: 400 });
    }

    // Calculate totals
    let subtotal = 0;
    const lineItems = cart.items.map((item: any) => {
      const unitPrice = item.variant.price || item.variant.product.basePrice;
      const totalPrice = unitPrice * item.quantity;
      subtotal += totalPrice;
      return {
        price_data: {
          currency: 'usd',
          product_data: {
            name: `${item.variant.product.name} - ${item.variant.size} / ${item.variant.color}`,
            description: item.variant.product.description || undefined,
          },
          unit_amount: Math.round(unitPrice * 100), // Stripe uses cents
        },
        quantity: item.quantity,
      };
    });

    const tax = subtotal * 0.08; // 8% tax
    const shipping = subtotal >= 100 ? 0 : 9.99; // Free shipping over $100
    const total = subtotal + tax + shipping;

    // Add tax and shipping as line items
    if (tax > 0) {
      lineItems.push({
        price_data: {
          currency: 'usd',
          product_data: {
            name: 'Tax',
            description: 'Sales tax',
          },
          unit_amount: Math.round(tax * 100),
        },
        quantity: 1,
      });
    }

    if (shipping > 0) {
      lineItems.push({
        price_data: {
          currency: 'usd',
          product_data: {
            name: 'Shipping',
            description: 'Standard shipping',
          },
          unit_amount: Math.round(shipping * 100),
        },
        quantity: 1,
      });
    }

    // Create order in pending state
    const orderNumber = generateOrderNumber();
    const orderItems = cart.items.map((item: any) => ({
      productId: item.variant.productId,
      variantId: item.variantId,
      quantity: item.quantity,
      unitPrice: item.variant.price || item.variant.product.basePrice,
      totalPrice: (item.variant.price || item.variant.product.basePrice) * item.quantity,
    }));

    const order = await prisma.swagOrder.create({
      data: {
        orderNumber,
        customerName,
        customerEmail,
        shippingAddress,
        billingAddress: billingAddress || shippingAddress,
        subtotal,
        tax,
        shipping,
        total,
        status: 'pending',
        paymentStatus: 'pending',
        paymentMethod: 'stripe',
        items: {
          create: orderItems,
        },
      },
    });

    // Initialize autonomous workflow execution
    const executionId = await initializeOrderExecution(order.id, orderNumber);
    await prisma.swagOrder.update({
      where: { id: order.id },
      data: { workflowExecutionId: executionId },
    });

    // Log agent action
    await logAgentAction({
      context: {
        executionId,
        orderId: order.id,
        orderNumber,
        agentName: 'CheckoutAgent',
        timestamp: new Date(),
      },
      actionType: 'create_checkout_session',
      targetEntity: 'order',
      targetId: order.id,
      inputData: { customerEmail, cartItemCount: cart.items.length },
      outputData: { orderNumber, total, executionId },
    });

    // Get origin for redirect URLs
    const headersList = await headers();
    const origin = headersList.get('origin') || headersList.get('x-forwarded-host') 
      ? `https://${headersList.get('x-forwarded-host')}` 
      : process.env.NEXTAUTH_URL || 'http://localhost:3000';

    // Create Stripe Checkout Session
    const stripeResponse = await fetch('https://api.stripe.com/v1/checkout/sessions', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${STRIPE_SECRET_KEY}`,
        'Content-Type': 'application/x-www-form-urlencoded',
        'Stripe-Version': STRIPE_API_VERSION,
      },
      body: new URLSearchParams({
        'mode': 'payment',
        'success_url': `${origin}/swag-store/success?session_id={CHECKOUT_SESSION_ID}`,
        'cancel_url': `${origin}/swag-store/cart`,
        'customer_email': customerEmail,
        'client_reference_id': order.id,
        'metadata[order_id]': order.id,
        'metadata[order_number]': orderNumber,
        ...lineItems.reduce((acc: any, item: any, idx: number) => {
          acc[`line_items[${idx}][price_data][currency]`] = item.price_data.currency;
          acc[`line_items[${idx}][price_data][product_data][name]`] = item.price_data.product_data.name;
          if (item.price_data.product_data.description) {
            acc[`line_items[${idx}][price_data][product_data][description]`] = item.price_data.product_data.description;
          }
          acc[`line_items[${idx}][price_data][unit_amount]`] = item.price_data.unit_amount.toString();
          acc[`line_items[${idx}][quantity]`] = item.quantity.toString();
          return acc;
        }, {} as Record<string, string>),
      }),
    });

    if (!stripeResponse.ok) {
      const errorData = await stripeResponse.json();
      console.error('Stripe error:', errorData);
      return NextResponse.json(
        { error: 'Failed to create checkout session', details: errorData },
        { status: 500 }
      );
    }

    const stripeSession = await stripeResponse.json();

    // Update order with Stripe session ID
    await prisma.swagOrder.update({
      where: { id: order.id },
      data: { stripeSessionId: stripeSession.id },
    });

    return NextResponse.json({
      sessionId: stripeSession.id,
      sessionUrl: stripeSession.url,
      orderId: order.id,
      orderNumber,
    });
  } catch (error) {
    console.error('Checkout error:', error);
    return NextResponse.json(
      { error: 'Failed to create checkout session' },
      { status: 500 }
    );
  }
}
