import { NextRequest, NextResponse } from "next/server";
import { authenticate } from "@/lib/authenticate";
import dbConnect from "@/lib/mongodb";
import Order from "@/models/Order";

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

    const authUser = await authenticate(request);

    const orders = await Order.find({
      userId: authUser.userId,
    })
      .sort({ createdAt: -1 });

    return NextResponse.json(
      {
        success: true,
        data: orders,
      },
      {
        status: 200,
      }
    );
  } catch (error: any) {
    return NextResponse.json(
      {
        success: false,
        message: error.message || "Unauthorized",
      },
      {
        status: 401,
      }
    );
  }
}