import { NextRequest, NextResponse } from 'next/server';
import dbConnect from '../../lib/mongodb';
import Order from '../../models/Order';

export async function POST(request: NextRequest) {
  try {
    await dbConnect();

    const body = await request.json();
    const {
      customer_id,
      guest_id,
      customer_name,
      customer_phone,
      customer_email,
      items,
      delivery_address,
      billing_address,
      payment_method = 'cod',
      payment_id,
      shipping_charge = 0,
      discount = 0,
      subtotal,
      total_amount,
      device = 'website',
    } = body;

    // Either logged in customer or guest
    if (!customer_id && !guest_id) {
      return NextResponse.json(
        {
          success: false,
          error: 'Customer ID or Guest ID is required',
        },
        { status: 400 }
      );
    }

    // Customer validation
    if (!customer_name || !customer_phone || !customer_email) {
      return NextResponse.json(
        {
          success: false,
          error: 'Customer details are required',
        },
        { status: 400 }
      );
    }

    // Items validation
    if (!Array.isArray(items) || items.length === 0) {
      return NextResponse.json(
        {
          success: false,
          error: 'At least one item is required',
        },
        { status: 400 }
      );
    }

    // Validate each item has required fields
    for (const item of items) {
      if (!item.product_id || !item.product_sku || !item.product_name || !item.price || !item.quantity) {
        return NextResponse.json(
          {
            success: false,
            error: 'Each item must have product_id, product_sku, product_name, price, and quantity',
          },
          { status: 400 }
        );
      }
    }

    // Delivery address validation
    if (
      !delivery_address ||
      !delivery_address.full_name ||
      !delivery_address.phone ||
      !delivery_address.address_line1 ||
      !delivery_address.city ||
      !delivery_address.state ||
      !delivery_address.pincode
    ) {
      return NextResponse.json(
        {
          success: false,
          error: 'Valid delivery address is required',
        },
        { status: 400 }
      );
    }

    // Billing address validation
    if (
      !billing_address ||
      !billing_address.full_name ||
      !billing_address.phone ||
      !billing_address.address_line1 ||
      !billing_address.city ||
      !billing_address.state ||
      !billing_address.pincode
    ) {
      return NextResponse.json(
        {
          success: false,
          error: 'Valid billing address is required',
        },
        { status: 400 }
      );
    }

    // Normalize items - ensure all required fields
    const orderItems = items.map((item: any) => {
      const price = Number(item.price);
      const quantity = Number(item.quantity);
      const itemSubtotal = item.subtotal || (price * quantity);

      return {
        product_id: item.product_id,
        product_sku: item.product_sku,
        product_name: item.product_name,
        price: price,
        quantity: quantity,
        subtotal: itemSubtotal,
      };
    });

    // Use provided subtotal or calculate from items
    const finalSubtotal = subtotal || orderItems.reduce((sum, item) => sum + item.subtotal, 0);
    
    // Use provided total_amount or calculate
    const finalTotalAmount = total_amount || (finalSubtotal + Number(shipping_charge) - Number(discount));

    // Payment status
    let payment_status: 'pending' | 'paid' = 'pending';
    if ((payment_method === 'online' || payment_method === 'upi') && payment_id) {
      payment_status = 'paid';
    }

    // Prepare order data
    const orderData = {
      customer_id: customer_id || null,
      guest_id: guest_id || null,
      customer_name: customer_name.trim(),
      customer_phone: customer_phone.trim(),
      customer_email: customer_email.trim().toLowerCase(),
      items: orderItems,
      delivery_address: {
        full_name: delivery_address.full_name.trim(),
        phone: delivery_address.phone.trim(),
        address_line1: delivery_address.address_line1.trim(),
        address_line2: delivery_address.address_line2?.trim() || '',
        city: delivery_address.city.trim(),
        state: delivery_address.state,
        pincode: delivery_address.pincode.trim(),
        country: delivery_address.country || 'India',
      },
      billing_address: {
        full_name: billing_address.full_name.trim(),
        phone: billing_address.phone.trim(),
        address_line1: billing_address.address_line1.trim(),
        address_line2: billing_address.address_line2?.trim() || '',
        city: billing_address.city.trim(),
        state: billing_address.state,
        pincode: billing_address.pincode.trim(),
        country: billing_address.country || 'India',
      },
      payment_method,
      payment_status,
      payment_id: payment_id || null,
      subtotal: finalSubtotal,
      shipping_charge: Number(shipping_charge),
      discount: Number(discount),
      total_amount: finalTotalAmount,
      order_status: 'pending',
      device,
      order_placed_at: new Date(),
    };

    // Log the order data for debugging
    console.log('Creating order with data:', JSON.stringify(orderData, null, 2));

    const order = await Order.create(orderData);

    return NextResponse.json(
      {
        success: true,
        message: 'Order placed successfully',
        data: order,
      },
      { status: 200 }
    );
  } catch (error: any) {
    console.error('Order POST Error:', error);
    
    // Handle validation errors
    if (error.name === 'ValidationError') {
      const validationErrors = Object.values(error.errors).map((err: any) => err.message);
      return NextResponse.json(
        {
          success: false,
          error: 'Validation failed',
          details: validationErrors,
        },
        { status: 400 }
      );
    }

    return NextResponse.json(
      {
        success: false,
        error: error|| 'Failed to create order',
      },
      { status: 500 }
    );
  }
}

export async function GET(request: NextRequest) {
  try {
    await dbConnect();

    const { searchParams } = new URL(request.url);

    const customer_id = searchParams.get("customer_id");

    if (!customer_id) {
      return NextResponse.json(
        {
          success: false,
          error: "Customer ID is required",
        },
        { status: 400 }
      );
    }

    const orders = await Order.find({ customer_id })
      .sort({ order_placed_at: -1 });

    return NextResponse.json({
      success: true,
      orders,
    });
  } catch (error: any) {
    return NextResponse.json(
      {
        success: false,
        error: error.message,
      },
      { status: 500 }
    );
  }
}