import { NextRequest, NextResponse } from "next/server";
import db from "@/lib/db";
import { getLogger } from "@/utils/logger";

import { getServerSession } from "next-auth";
import { UserRole } from "@prisma/client";
import { authOptions } from "../../auth/[...nextauth]/auth-options";


// MAJOR FIX REQUIRED HERE - Completed and fixed by Shamir Roy
// CAUTION: This file is critical for the admin customers page API. Any misuse of the API or incorrect data handling can lead to significant issues and security vulnerabilities in the admin interface.

const logger = getLogger("api/customers");


export async function GET(request: NextRequest){

  try {

    const {searchParams} = new URL(request.url)
    const page = parseInt(searchParams.get("page") || "1")
    const limit = parseInt(searchParams.get("limit") || "10")

    
    const session = await getServerSession(authOptions)

    if (!session?.user.role || session?.user.role !== UserRole.ADMIN) {
      return NextResponse.json({ message: "You are not authorized!" }, { status: 403 });
    }

    const users = await db.user.findMany({ 
      include: {
        profile: true,
      },
      skip: (page - 1) * limit,
      take: limit
    })

    const totalCount = await db.user.count()

    return NextResponse.json({users: users, limit: limit, page: page, total: totalCount}, {status: 200})

  }
  catch (error: any) {

    logger.error("Error fetching customers: ", error?.config?.message || error?.message);
    return NextResponse.json(
      { message: "Failed to fetch customers" },
      { status: 500 }
    )
  }

}