import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { z } from 'zod';
import { executePayment } from '@/lib/myfatoorah';

const orderItemSchema = z.object({
  productId: z.string(),
  name: z.string(),
  nameAr: z.string(),
  price: z.number().positive(),
  quantity: z.number().int().positive(),
  image: z.string().optional()
});

const orderSchema = z.object({
  userId: z.string(),
  address: z.object({
    firstName: z.string().optional(),
    lastName: z.string().optional(),
    phone: z.string().min(8),
    email: z.string().email().optional(),
    area: z.string(),
    block: z.string().optional(),
    street: z.string().optional(),
    building: z.string().optional(),
    notes: z.string().optional()
  }),
  items: z.array(orderItemSchema).min(1),
  paymentMethod: z.enum(['knet', 'visa', 'apple', 'cod']),
  coupon: z.string().optional(),
  loyaltyPointsUsed: z.number().int().nonnegative().optional()
});

export async function GET() {
  try {
    const orders = await prisma.order.findMany({
      include: { items: true }
    });
    return NextResponse.json({ success: true, orders });
  } catch (error: any) {
    return NextResponse.json({ success: false, message: error.message }, { status: 500 });
  }
}

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const validatedData = orderSchema.parse(body);
    
    // SECURITY: Fetch real prices from Database to prevent frontend price manipulation
    const dbProducts = await prisma.product.findMany({
      where: { id: { in: validatedData.items.map(i => i.productId) } },
      select: { id: true, price: true, stock: true }
    });

    let subtotal = 0;
    const validatedItems = validatedData.items.map(item => {
      const dbProduct = dbProducts.find(p => p.id === item.productId);
      if (!dbProduct) throw new Error(`Product ID ${item.productId} not found`);
      if (dbProduct.stock < item.quantity) throw new Error(`Insufficient stock for ${item.name}`);
      
      subtotal += dbProduct.price * item.quantity;
      return { ...item, price: dbProduct.price }; // Overwrite with true DB price
    });

    const shipping = subtotal > 15 ? 0 : 1.5;
    
    const discountFromCoupon = 0; // TODO: Integrate real coupon DB fetch
    const loyaltyDiscount = (validatedData.loyaltyPointsUsed || 0) * 0.01;
    const discount = discountFromCoupon + loyaltyDiscount;
    const total = Math.max(0, subtotal - discount + shipping);
    const loyaltyPointsEarned = Math.floor(total * 10);
    
    const order = await prisma.order.create({
      data: {
        userId: validatedData.userId,
        customerName: `${validatedData.address.firstName || ''} ${validatedData.address.lastName || ''}`.trim(),
        phone: validatedData.address.phone,
        email: validatedData.address.email,
        address: validatedData.address,
        subtotal,
        discount,
        shipping,
        total,
        coupon: validatedData.coupon,
        paymentMethod: validatedData.paymentMethod,
        paymentStatus: validatedData.paymentMethod === 'cod' ? 'pending' : 'pending',
        status: 'placed',
        loyaltyPointsEarned,
        loyaltyPointsUsed: validatedData.loyaltyPointsUsed || 0,
        items: {
          create: validatedItems.map(item => ({
            productId: item.productId,
            name: item.name,
            nameAr: item.nameAr,
            price: item.price,
            quantity: item.quantity,
            image: item.image,
          }))
        }
      },
      include: { items: true }
    });

    if (validatedData.paymentMethod !== 'cod') {
      const paymentMethodId = validatedData.paymentMethod === 'knet' ? 1 : 2;
      
      const paymentResult = await executePayment({
        invoiceValue: total,
        customerName: order.customerName,
        customerEmail: order.email || undefined,
        customerMobile: order.phone,
        orderId: order.id,
        paymentMethodId
      });

      return NextResponse.json({ success: true, order, paymentUrl: paymentResult.paymentUrl }, { status: 201 });
    }

    return NextResponse.json({ success: true, order }, { status: 201 });
  } catch (error: any) {
    if (error instanceof z.ZodError) {
      return NextResponse.json({ success: false, message: 'Validation error', errors: error.flatten() }, { status: 400 });
    }
    return NextResponse.json({ success: false, message: error.message }, { status: 500 });
  }
}

export const dynamic = 'force-dynamic';
