// app/api/admin/users/route.ts
import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth-options';
import { prisma } from '@/lib/prisma';

export async function GET(req: Request) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.email) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const role = (session as any)?.user?.role ?? null;
    if (!(role === 'admin' || role === 'superadmin')) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    // Fetch all users with enrollments and last activity
    const users = await prisma.user.findMany({
      select: {
        id: true,
        email: true,
        name: true,
        image: true,
        role: true,
        createdAt: true,
        enrollments: {
          select: {
            course: {
              select: {
                id: true,
                title: true,
              },
            },
          },
        },
        progress: {
          select: {
            updatedAt: true,
          },
          orderBy: {
            updatedAt: 'desc',
          },
          take: 1,
        },
      },
      orderBy: {
        createdAt: 'desc',
      },
    });

    // Map to include last activity
    const usersWithActivity = users.map((user) => ({
      ...user,
      lastActivity: user.progress[0]?.updatedAt ?? null,
      progress: undefined, // Remove the progress array
    }));

    return NextResponse.json(usersWithActivity);
  } catch (err: any) {
    console.error('fetch users error', err);
    return NextResponse.json(
      { error: err?.message ?? 'server error' },
      { status: 500 }
    );
  }
}
