// Mock Stripe Webhook for Testing
// Simulates Stripe events when real keys aren't configured
export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/db';
import { processPaymentConfirmed } from '@/lib/order-to-cash/orchestrator';

// Generate a unique order number
function generateOrderNumber(): string {
  const date = new Date();
  const dateStr = date.toISOString().slice(2, 10).replace(/-/g, '');
  const random = Math.random().toString(36).substring(2, 6).toUpperCase();
  return `GFS-${dateStr}-${random}`;
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { eventType, orderId, amount, customerEmail, customerName } = body;
    
    if (eventType === 'checkout.session.completed') {
      // Create a mock order if it doesn't exist
      let order = orderId 
        ? await prisma.swagOrder.findUnique({ where: { id: orderId } })
        : null;
      
      if (!order) {
        const orderAmount = amount || 49.99;
        // Create a test order
        order = await prisma.swagOrder.create({
          data: {
            orderNumber: generateOrderNumber(),
            customerName: customerName || 'Test Customer',
            customerEmail: customerEmail || 'test@example.com',
            shippingAddress: '123 Test Street, Test City, TS 12345',
            items: JSON.parse(JSON.stringify([
              { productId: 'test-product', name: 'Test Swag Item', quantity: 1, price: orderAmount }
            ])),
            subtotal: orderAmount,
            tax: orderAmount * 0.08,
            shipping: 5.99,
            total: orderAmount * 1.08 + 5.99,
            status: 'pending',
            stripeSessionId: `cs_mock_${Date.now()}`,
            stripePaymentIntentId: `pi_mock_${Date.now()}`,
            stripeCustomerId: `cus_mock_${Date.now()}`,
          },
        });
      }
      
      // Update order status
      await prisma.swagOrder.update({
        where: { id: order.id },
        data: {
          status: 'paid',
          stripePaymentIntentId: `pi_mock_${Date.now()}`,
        },
      });
      
      // Trigger the autonomous order-to-cash flow
      await processPaymentConfirmed(order.id, `pi_mock_${Date.now()}`);
      
      return NextResponse.json({
        success: true,
        message: 'Mock checkout completed',
        orderId: order.id,
        orderNumber: order.orderNumber,
        flow: 'Order → Invoice → Transaction → AR created',
      });
    }
    
    if (eventType === 'payment_intent.succeeded') {
      return NextResponse.json({
        success: true,
        message: 'Mock payment succeeded event received',
      });
    }
    
    if (eventType === 'payout.paid') {
      // Create a mock payout record
      await prisma.stripePayoutRecord.create({
        data: {
          stripePayoutId: `po_mock_${Date.now()}`,
          amount: amount || 299.99,
          currency: 'USD',
          status: 'paid',
          arrivalDate: new Date(),
          paymentIntentIds: JSON.parse(JSON.stringify(['pi_mock_001', 'pi_mock_002'])),
        },
      });
      
      return NextResponse.json({
        success: true,
        message: 'Mock payout recorded',
      });
    }
    
    return NextResponse.json({
      success: false,
      error: 'Unknown event type',
    }, { status: 400 });
    
  } catch (error) {
    console.error('[Mock Stripe] Error:', error);
    return NextResponse.json(
      { error: 'Failed to process mock event', details: String(error) },
      { status: 500 }
    );
  }
}

// GET endpoint to check mock status and create test data
export async function GET() {
  try {
    const isStripeConfigured = process.env.STRIPE_SECRET_KEY && 
      !process.env.STRIPE_SECRET_KEY.startsWith('sk_placeholder');
    
    const orderCount = await prisma.swagOrder.count();
    const arCount = await prisma.accountsReceivable.count();
    const payoutCount = await prisma.stripePayoutRecord.count();
    
    return NextResponse.json({
      mockMode: !isStripeConfigured,
      message: isStripeConfigured 
        ? 'Stripe is configured - use real webhooks' 
        : 'Mock mode active - use POST /api/stripe/mock to simulate events',
      stats: {
        orders: orderCount,
        accountsReceivable: arCount,
        payouts: payoutCount,
      },
      testEndpoints: {
        simulateCheckout: 'POST /api/stripe/mock with { eventType: "checkout.session.completed", amount: 99.99 }',
        simulatePayout: 'POST /api/stripe/mock with { eventType: "payout.paid", amount: 299.99 }',
      },
    });
  } catch (error) {
    return NextResponse.json({ error: String(error) }, { status: 500 });
  }
}
