import db from "@/lib/db";
import { NextRequest, NextResponse } from "next/server";
import { getLogger } from "@/utils/logger";
import { authOptions } from "@/app/api/auth/[...nextauth]/auth-options";
import { getServerSession } from "next-auth";

const logger = getLogger("api/orders");

export const GET = async (req: NextRequest) => {
  try {

    const { searchParams } = new URL(req.url)

    const page = parseInt(searchParams.get('page') || "1")
    const limit = parseInt(searchParams.get('limit') || "10")



    const session = await getServerSession(authOptions);

    if (!session?.user.profileId) {
      return NextResponse.json({ mssg: 'Login first' }, { status: 401 });
    }



    const orders = await db.orders.findMany({
      where: {
        profile_id: session.user.profileId
      },
      orderBy: {
        id: "desc"
      },
      skip: (page - 1) * limit,
      take: limit
    })

    const totalOrders = await db.orders.count({
      where: {
        profile_id: session.user.profileId
      }
    })


    return NextResponse.json({ orders, total: totalOrders, page: page, limit: limit }, { status: 200 })

  } catch (error: any) {
    logger.error("Error occurred when fetching orders", {
      errorMsg: error.message,
      errorStack: error.stack,
      errorMeta: error?.config?.data || null,
    });
    return new NextResponse("Internal Server Error", { status: 500 });
  }
}
