import { NextRequest, NextResponse } from "next/server";
import db from "@/lib/db";
import {getLogger} from "@/utils/logger";
import { authOptions } from "../../auth/[...nextauth]/auth-options";
import { getServerSession } from "next-auth";
import { UserRole } from "@prisma/client";


const logger = getLogger("/api/users");

// USE INDEXING TO FETCH ALL USERS DATA WHEN TOTAL NUMBER OF USERS EXCEEDS 1000
// DON'T USE THIS API UNLESS YOU REALLY NEED IT. 
// ONLY ADMINS ARE ALLOWED TO USE THIS API AND ACCESS ITS DATA.

export async function GET(req: NextRequest) {
  try {

    const session = await getServerSession(authOptions);

    if (!session || session.user.role != UserRole.ADMIN){
      return NextResponse.json({"error":"You are not authorized to have access to this data!"})
    }

    const allUsers = await db.user.findMany({});

    return NextResponse.json(
      {
        users: allUsers,
        message: "All user data fetched successfully ",
      },
      { status: 201 }
    );
  } catch (error:any) {
    logger.error("An error occured while fetching all users", {
      error: error?.config?.data ?? error?.message ?? "Unknown error"
    })
    return new NextResponse("Internal server error", { status: 500 });
  }
}
