import { NextResponse } from "next/server";
import { ObjectId } from "mongodb";
import { getCollection } from "@/lib/mongodb";

export async function PATCH(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    
    if (!id) {
      return NextResponse.json({ error: "Order ID is required" }, { status: 400 });
    }

    // Validate ObjectId format
    if (!ObjectId.isValid(id)) {
      return NextResponse.json({ error: "Invalid order ID format" }, { status: 400 });
    }

    const body = await request.json().catch(() => ({}));
    const status = body?.status as string | undefined;
    const customerName = body?.customer?.name as string | undefined;

    const updateSet: Record<string, any> = {};

    // Optional status update
    if (typeof status === "string") {
      const allowed = ["pending", "processing", "completed", "cancelled"];
      if (!allowed.includes(status)) {
        return NextResponse.json(
          { error: `Invalid status. Allowed: ${allowed.join(", ")}` },
          { status: 400 }
        );
      }
      updateSet.status = status;
    }

    // Optional customer name update
    if (typeof customerName === "string") {
      if (!customerName.trim()) {
        return NextResponse.json({ error: "Customer name cannot be empty" }, { status: 400 });
      }
      updateSet["customer.name"] = customerName.trim();
    }

    if (Object.keys(updateSet).length === 0) {
      return NextResponse.json({ error: "No valid fields to update" }, { status: 400 });
    }

    const orders = await getCollection<any>("orders");
    const updatedAt = new Date().toISOString();
    
    // Use updateOne and then fetch the updated document
    const updateResult = await orders.updateOne(
      { _id: new ObjectId(id) },
      { $set: { ...updateSet, updatedAt } }
    );

    if (updateResult.matchedCount === 0) {
      return NextResponse.json({ error: "Order not found" }, { status: 404 });
    }

    // Fetch the updated document
    const updatedDoc = await orders.findOne({ _id: new ObjectId(id) });

    if (!updatedDoc) {
      return NextResponse.json({ error: "Order not found after update" }, { status: 404 });
    }

    return NextResponse.json({
      success: true,
      updated: {
        _id: updatedDoc._id.toString(),
        status: updatedDoc.status,
        updatedAt: updatedDoc.updatedAt || updatedAt,
      },
    });
  } catch (error) {
    console.error("Error updating order status:", error);
    return NextResponse.json(
      { error: "Failed to update order status", details: error instanceof Error ? error.message : "Unknown error" },
      { status: 500 }
    );
  }
}
