import { CanActivate, ExecutionContext, Injectable, NotFoundException } from '@nestjs/common';
import { UserRole } from '@prisma/client';

@Injectable()
export class RequireTenantGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const user = request.user;
    const tenantContext = request.tenantContext;

    // Per plan.md architecture rule:
    // Platform Admin has no tenantId (null) and must NEVER have direct access to tenant CRM records.
    // Any query by Platform Admin to tenant CRM endpoints returns 404.
    if (!user || user.role === UserRole.PLATFORM_ADMIN || !tenantContext?.tenantId) {
      throw new NotFoundException('Resource not found');
    }

    return true;
  }
}
