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

// ✅ Helper: Generate Order ID (if not using schema middleware)
function generateOrderId() {
    const random = Math.random().toString(36).substring(2, 6).toUpperCase();
    return `NC${Date.now()}${random}`;
}

export async function GET(request: NextRequest, context?: { params: Promise<any> }) {
    try {
        await dbConnect();

        const { searchParams } = new URL(request.url);
        const page = parseInt(searchParams.get('page') || '1');
        const limit = parseInt(searchParams.get('limit') || '10');
        const search = searchParams.get('search');
        const status = searchParams.get('status');
        const sort = searchParams.get('sort') || 'createdAt';
        const order = searchParams.get('order') || 'desc';

        let query: any = {};

        // Search functionality
        if (search) {
            query.$or = [
                { customer_name: { $regex: search, $options: 'i' } },
                { customer_email: { $regex: search, $options: 'i' } },
                { order_id: { $regex: search, $options: 'i' } }
            ];
        }

        // Status filter
        if (status && status !== 'all') {
            query.order_status = status;
        }

        const skip = (page - 1) * limit;
        const sortOrder = order === 'asc' ? 1 : -1;

        const orders = await Order.find(query)
            .sort({ [sort]: sortOrder })
            .skip(skip)
            .limit(limit);

        const total = await Order.countDocuments(query);

        return NextResponse.json({
            success: true,
            data: orders,
            pagination: {
                page,
                limit,
                total,
                pages: Math.ceil(total / limit)
            }
        });

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

// ✅ POST (Create order)
export async function POST(request: NextRequest) {
    try {
        await dbConnect();

        const body = await request.json();

        const {
            customer_name,
            customer_phone,
            customer_email,
            total_amount,
            device
        } = body;

        // ✅ Validation
        if (!customer_name?.trim()) {
            return NextResponse.json(
                { success: false, error: 'Customer name is required' },
                { status: 400 }
            );
        }

        if (!customer_phone?.trim()) {
            return NextResponse.json(
                { success: false, error: 'Customer phone is required' },
                { status: 400 }
            );
        }

        if (!customer_email?.trim()) {
            return NextResponse.json(
                { success: false, error: 'Customer email is required' },
                { status: 400 }
            );
        }

        if (!total_amount || total_amount <= 0) {
            return NextResponse.json(
                { success: false, error: 'Valid total amount is required' },
                { status: 400 }
            );
        }

        // ✅ Create order
        const order = await Order.create({
            order_id: generateOrderId(), // optional if schema already handles it
            customer_name: customer_name.trim(),
            customer_phone: customer_phone.trim(),
            customer_email: customer_email.trim(),
            total_amount,
            device: device || 'website'
        });

        return NextResponse.json({
            success: true,
            data: order,
            message: 'Order created successfully'
        });

    } catch (error: any) {
        console.error('Error creating order:', error);

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

// ✅ PUT (Update order by ID)
export async function PUT(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
    try {
        await dbConnect();

        const { id } = await params;
        const body = await request.json();

        const {
            customer_name,
            customer_phone,
            customer_email,
            total_amount,
            device,
            order_status
        } = body;

        // ✅ Check if order exists
        const existingOrder = await Order.findById(id);

        if (!existingOrder) {
            return NextResponse.json(
                { success: false, error: 'Order not found' },
                { status: 404 }
            );
        }

        // ✅ Validation
        if (customer_name !== undefined && !customer_name?.trim()) {
            return NextResponse.json(
                { success: false, error: 'Customer name cannot be empty' },
                { status: 400 }
            );
        }

        if (customer_phone !== undefined && !customer_phone?.trim()) {
            return NextResponse.json(
                { success: false, error: 'Customer phone cannot be empty' },
                { status: 400 }
            );
        }

        if (customer_email !== undefined && !customer_email?.trim()) {
            return NextResponse.json(
                { success: false, error: 'Customer email cannot be empty' },
                { status: 400 }
            );
        }

        if (total_amount !== undefined && total_amount <= 0) {
            return NextResponse.json(
                { success: false, error: 'Valid total amount is required' },
                { status: 400 }
            );
        }

        // ✅ Build update object (only update provided fields)
        const updateData: any = {};

        if (customer_name !== undefined) updateData.customer_name = customer_name.trim();
        if (customer_phone !== undefined) updateData.customer_phone = customer_phone.trim();
        if (customer_email !== undefined) updateData.customer_email = customer_email.trim();
        if (total_amount !== undefined) updateData.total_amount = total_amount;
        if (device !== undefined) updateData.device = device;
        if (order_status !== undefined) updateData.order_status = order_status;

        // ✅ Update order
        const updatedOrder = await Order.findByIdAndUpdate(
            id,
            { $set: updateData },
            { new: true, runValidators: true }
        );

        return NextResponse.json({
            success: true,
            data: updatedOrder,
            message: 'Order updated successfully'
        });

    } catch (error: any) {
        console.error('Error updating order:', error);

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