import { NextResponse } from "next/server";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export async function POST(req: Request) {
  try {
    const body = await req.json();
    const { 
      items, 
      totalAmount, 
      shippingAddress, 
      shippingWilaya, 
      shippingCommune, 
      customerPhone, 
      customerName, 
      customerEmail 
    } = body;

    if (!items || items.length === 0 || !shippingAddress || !customerPhone || !customerName) {
      return NextResponse.json(
        { message: "Missing required fields" },
        { status: 400 }
      );
    }

    const newOrder = await prisma.order.create({
      data: {
        items: JSON.stringify(items),
        totalAmount,
        shippingAddress,
        shippingWilaya,
        shippingCommune,
        customerPhone,
        customerName,
        customerEmail,
        status: "PENDING",
        paymentMethod: "COD"
      },
    });

    return NextResponse.json(
      { message: "Order placed successfully", orderId: newOrder.id },
      { status: 201 }
    );
  } catch (error) {
    console.error("Order error:", error);
    return NextResponse.json(
      { message: "An error occurred while placing the order" },
      { status: 500 }
    );
  }
}
