import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import type { Observable } from 'rxjs';
import type { AccessTokenPayload } from '@pac/types';
import type { TenantScopeContext } from '../decorators/tenant-scope.decorator';

/**
 * Pulls host_id / tenant_id / clinic_ids out of the JWT payload and attaches
 * a normalized TenantScopeContext to the request, so handlers and services can
 * grab it via the @TenantScope() decorator without re-reading the token.
 *
 * The interceptor never invents a scope: if the request is unauthenticated
 * (public routes), it leaves the request untouched.
 */
@Injectable()
export class TenantScopeInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
    const req = context.switchToHttp().getRequest<{
      user?: AccessTokenPayload;
      tenantScope?: TenantScopeContext;
    }>();
    if (req.user) {
      req.tenantScope = {
        hostId: req.user.hostId,
        tenantId: req.user.tenantId,
        clinicIds: req.user.clinicIds ?? [],
        userId: req.user.sub,
      };
    }
    return next.handle();
  }
}
