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

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

    const wantsUsers = isAdmin || canUserMod;
    const wantsListings = isAdmin || canListingMod;

    const [users, listings] = await Promise.all([
      wantsUsers ? prisma.user.count({ where: { status: UserStatus.PENDING } }) : Promise.resolve(0),
      wantsListings ? prisma.listing.count({ where: { status: ListingStatus.PENDING, removedAt: null } }) : Promise.resolve(0),
    ]);

    return NextResponse.json({ users, listings, total: users + listings });
  } catch (error) {
    if (String(error).includes('Unauthorized')) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    console.error('Pending count error', error);
    return NextResponse.json({ error: 'Failed to load count' }, { status: 500 });
  }
}
export const dynamic = 'force-dynamic';
