import { createResponse, handleApiError, PAGE_SIZE } from '@/src/lib/api';
import { getSession } from '@/src/lib/auth';
import { db } from '@/src/lib/db';
import { Prisma } from '@prisma/client';

export async function GET(req: Request) {
  try {
    const session = await getSession();

    const searchParams = new URL(req.url).searchParams;
    const search = searchParams.get('search') ?? '';
    const page = parseInt(searchParams.get('page') ?? '1');
    const isAdmin = session?.user?.role === 'ADMIN';
    const baseSearchCondition: Prisma.UserWhereInput = {
      OR: [
        { username: { contains: search, mode: 'insensitive' as Prisma.QueryMode } },
        { email: { contains: search, mode: 'insensitive' as Prisma.QueryMode } },
      ],
      NOT: {
        id: session?.user?.id,
      }
    };

    const [users, total] = await db.$transaction([
      db.user.findMany({
        where: baseSearchCondition,
        select: {
          email: true,
          username: true,
          id: true,
          role: true,
        },
        take: !isAdmin ? undefined : PAGE_SIZE,
        skip: !isAdmin ? undefined : (page - 1) * PAGE_SIZE,
      }),
      db.user.count({
        where: baseSearchCondition,
      }),
    ]);

    return createResponse(200, 'Users fetched successfully', {
      data: users,
      pagination: {
        page,
        total,
        totalPages: Math.ceil(total / PAGE_SIZE),
      },
    });
  } catch (error) {
    return handleApiError(error);
  }
}
