import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { Principal } from '../../auth/principal';

// The CA/broker-cert routes are global (not nested under /orgs/:orgId/...),
// so OrgRolesGuard doesn't apply — it hard-requires an :orgId route param.
// Gate: any authenticated user with an ORG_ADMIN membership in *some* org.
@Injectable()
export class RequireAnyOrgAdminGuard implements CanActivate {
  constructor(private readonly prisma: PrismaService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const req = context.switchToHttp().getRequest();
    const principal: Principal | undefined = req.user;
    if (!principal || principal.type !== 'user') {
      throw new ForbiddenException('Organization admin required');
    }

    const membership = await this.prisma.orgMembership.findFirst({
      where: { userId: principal.userId, role: 'ORG_ADMIN' },
    });
    if (!membership) {
      throw new ForbiddenException('Requires ORG_ADMIN in at least one organization');
    }
    return true;
  }
}
