import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/db';
import { cookies } from 'next/headers';
import { z } from 'zod';
import { validateBody } from '@/lib/api-validation';

export const dynamic = 'force-dynamic';

const createOrderSchema = z.object({
  customerName: z.string().min(1, 'Customer name is required').max(200),
  customerEmail: z.string().email('Valid email is required').max(255),
  shippingAddress: z.string().min(1, 'Shipping address is required').max(1000),
  billingAddress: z.string().max(1000).optional(),
  paymentMethod: z.string().min(1, 'Payment method is required').max(50),
});

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 GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const status = searchParams.get('status');
    const limit = parseInt(searchParams.get('limit') || '50');

    const where: any = {};
    if (status) where.status = status;

    const orders = await prisma.swagOrder.findMany({
      where,
      include: {
        items: {
          include: {
            product: true,
            variant: true,
          },
        },
      },
      orderBy: { createdAt: 'desc' },
      take: limit,
    });

    return NextResponse.json({ orders });
  } catch (error) {
    console.error('Error fetching orders:', error);
    return NextResponse.json({ error: 'Failed to fetch orders' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const result = await validateBody(request, createOrderSchema);
    if (result.error) return result.error;
    const { customerName, customerEmail, shippingAddress, billingAddress, paymentMethod } = result.data;
    const cookieStore = await cookies();
    const sessionId = cookieStore.get('swag_session')?.value;

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

    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 orderItems = cart.items.map((item: any) => {
      const unitPrice = item.variant.price || item.variant.product.basePrice;
      const totalPrice = unitPrice * item.quantity;
      subtotal += totalPrice;
      return {
        productId: item.variant.productId,
        variantId: item.variantId,
        quantity: item.quantity,
        unitPrice,
        totalPrice,
      };
    });

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

    // Create order with transaction
    const order = await prisma.$transaction(async (tx: any) => {
      // Create order
      const newOrder = await tx.swagOrder.create({
        data: {
          orderNumber: generateOrderNumber(),
          customerName,
          customerEmail,
          shippingAddress,
          billingAddress: billingAddress || shippingAddress,
          subtotal,
          tax,
          shipping,
          total,
          paymentMethod,
          status: 'confirmed',
          paymentStatus: 'paid', // Simulated payment
          items: {
            create: orderItems,
          },
        },
        include: { items: { include: { product: true, variant: true } } },
      });

      // Deduct stock and clear reservations
      for (const item of cart.items) {
        await tx.swagVariant.update({
          where: { id: item.variantId },
          data: {
            stock: { decrement: item.quantity },
            reserved: { decrement: item.quantity },
          },
        });
      }

      // Create accounting transaction
      const revenueAccount = await tx.account.findFirst({
        where: { name: { contains: 'Revenue', mode: 'insensitive' } },
      });

      if (revenueAccount) {
        await tx.transaction.create({
          data: {
            type: 'credit',
            accountId: revenueAccount.id,
            referenceNo: newOrder.orderNumber,
            description: `Swag Store Sale - ${newOrder.orderNumber}`,
            amount: total,
            status: 'completed',
            category: 'sales',
            metadata: {
              source: 'swag-store',
              orderId: newOrder.id,
              itemCount: orderItems.length,
            },
          },
        });
      }

      // Create inventory movements
      for (const item of cart.items) {
        const product = await tx.product.findFirst({
          where: { sku: item.variant.product.sku },
        });

        if (product) {
          await tx.stockMovement.create({
            data: {
              productId: product.id,
              type: 'sale',
              quantity: -item.quantity,
              reference: newOrder.orderNumber,
              reason: 'Swag store sale',
            },
          });
        }
      }

      // Mark cart as converted
      await tx.swagCart.update({
        where: { id: cart.id },
        data: { status: 'converted' },
      });

      // Delete cart items
      await tx.swagCartItem.deleteMany({
        where: { cartId: cart.id },
      });

      return newOrder;
    });

    // Clear cart cookie
    const response = NextResponse.json({ order });
    response.cookies.delete('swag_session');

    return response;
  } catch (error) {
    console.error('Error creating order:', error);
    return NextResponse.json({ error: 'Failed to create order' }, { status: 500 });
  }
}
