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,

      payment_method,
      payment_id,

      shipping_charge = 0,
      discount = 0,

      device = 'website',
    } = body;

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

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

    // Validate items
    if (!items || !Array.isArray(items) || items.length === 0) {
      return NextResponse.json(
        {
          success: false,
          error: 'Order items are required',
        },
        { status: 400 }
      );
    }

    // Validate address
    if (!delivery_address) {
      return NextResponse.json(
        {
          success: false,
          error: 'Delivery address is required',
        },
        { status: 400 }
      );
    }

    // Calculate subtotal
    const subtotal = items.reduce(
      (sum: number, item: any) =>
        sum + Number(item.price) * Number(item.quantity),
      0
    );

    // Calculate total amount
    const total_amount =
      subtotal + Number(shipping_charge) - Number(discount);

    // Create order
    const order = new Order({
      customer_id: customer_id || null,
      guest_id: guest_id || null,

      customer_name,
      customer_phone,
      customer_email,

      items: items.map((item: any) => ({
        product_id: item.product_id,
        product_sku: item.product_sku,
        product_name: item.product_name,

        price: Number(item.price),
        quantity: Number(item.quantity),

        subtotal:
          Number(item.price) * Number(item.quantity),
      })),

      delivery_address,

      payment_method,

      payment_status:
        payment_method === 'cod'
          ? 'pending'
          : 'paid',

      payment_id: payment_id || null,

      subtotal,
      shipping_charge,
      discount,
      total_amount,

      order_status: 'pending',

      device,
    });

    await order.save();

    return NextResponse.json(
      {
        success: true,
        message: 'Order created successfully',
        data: order,
      },
      { status: 201 }
    );
  } catch (err: any) {
    console.error('Order POST error:', err);

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