import { NextResponse } from 'next/server';
import { prisma } from '../../../../lib/prisma';
import { requireAuth } from '../../../../lib/jwt';
import { Role, UserStatus } from '@prisma/client';

export async function GET(req: Request) {
  try {
    const auth = await requireAuth(req);
    if (auth.role !== Role.ADMIN) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    const users = await prisma.user.findMany({
      select: {
        id: true,
        email: true,
        name: true,
        role: true,
        status: true,
        emailVerifiedAt: true,
        approvedAt: true,
        createdAt: true,
      },
      orderBy: { createdAt: 'asc' },
      take: 200,
    });

    return NextResponse.json({ users, roles: Object.values(Role), statuses: Object.values(UserStatus) });
  } catch (error) {
    if (String(error).includes('Unauthorized')) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    console.error('List users error', error);
    return NextResponse.json({ error: 'Failed to load users' }, { status: 500 });
  }
}
export const dynamic = 'force-dynamic';
