import { Prisma } from '@prisma/client';
import { PrismaService } from '../../../shared/prisma/prisma.service';

export type AuditViewerScope = {
  viewerId: bigint;
  viewerRole?: string | null;
  viewerUserType: string;
};

/** SUPER_ADMIN (and unrestricted legacy admins) see all audit rows. */
export function isAuditListUnrestricted(role?: string | null): boolean {
  return role === 'SUPER_ADMIN';
}

/**
 * Non–super-admin staff may only see audit rows whose operator shares their admin role,
 * or (for SUPPORT) player-initiated identity actions.
 */
export async function buildAuditListScopeWhere(
  prisma: PrismaService,
  scope: AuditViewerScope,
): Promise<Prisma.AuditLogWhereInput | undefined> {
  if (isAuditListUnrestricted(scope.viewerRole)) {
    return undefined;
  }

  if (!scope.viewerRole) {
    return { operatorId: scope.viewerId };
  }

  const sameRoleUsers = await prisma.user.findMany({
    where: { adminRole: { role: { code: scope.viewerRole } } },
    select: { id: true },
  });
  const sameRoleOperatorIds = sameRoleUsers.map((u) => u.id);

  const or: Prisma.AuditLogWhereInput[] = [{ operatorId: { in: sameRoleOperatorIds } }];

  // SUPPORT handles player account recovery; include player-initiated audit entries.
  if (scope.viewerRole === 'SUPPORT') {
    or.push({ operatorType: 'PLAYER' });
  }

  return { OR: or };
}
