import {
  Injectable,
  CanActivate,
  ExecutionContext,
  ForbiddenException,
} from '@nestjs/common';

/**
 * Guard que verifica que el usuario pertenezca al tenant.
 * Asegura que tenantId del token coincida con el contexto.
 */
@Injectable()
export class TenantMemberGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const user = request.user;

    if (!user) {
      throw new ForbiddenException('User not authenticated');
    }

    if (!user.tenantId) {
      throw new ForbiddenException('User not associated with any tenant');
    }

    // Si hay un tenant_id en params, verificar que coincida
    const paramTenantId = request.params?.tenantId || request.params?.tenant_id;
    if (paramTenantId && paramTenantId !== user.tenantId) {
      throw new ForbiddenException('Access denied to this tenant');
    }

    return true;
  }
}
