import type { GetLeagueAdminPermissionsUseCase } from '@core/racing/application/use-cases/GetLeagueAdminPermissionsUseCase';
import { ForbiddenException } from '@nestjs/common';
import { getActorFromRequestContext } from '../auth/getActorFromRequestContext';

type GetLeagueAdminPermissionsUseCaseLike = Pick<GetLeagueAdminPermissionsUseCase, 'execute'>;

export async function requireLeagueAdminOrOwner(
  leagueId: string,
  getLeagueAdminPermissionsUseCase: GetLeagueAdminPermissionsUseCaseLike,
): Promise<void> {
  const actor = getActorFromRequestContext();

  // Check for demo session roles - bypass database check
  if (actor.role && ['league-admin', 'league-owner', 'super-admin', 'system-owner'].includes(actor.role)) {
    return; // Allow access for demo admin roles
  }

  const permissionResult = await getLeagueAdminPermissionsUseCase.execute({
    leagueId,
    performerDriverId: actor.driverId,
  });

  if (permissionResult.isErr()) {
    throw new ForbiddenException('Forbidden');
  }
}