import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';
import { lastValueFrom, Observable } from 'rxjs';
import { IS_PUBLIC_KEY } from './public.decorator';
import { tenantStore } from '../tenant/tenant.store';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') implements CanActivate {
  constructor(private reflector: Reflector) {
    super();
  }

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (isPublic) {
      return true;
    }

    const result = await super.canActivate(context);
    let canActivate = false;

    if (result instanceof Observable) {
      canActivate = await lastValueFrom(result);
    } else {
      canActivate = result;
    }

    if (canActivate) {
      const request = context.switchToHttp().getRequest();
      const user = request.user;
      if (user) {
        const store = tenantStore.getStore();
        if (store) {
          store.tenantId = user.tenantId;
          store.userId = user.id;
        }
      }
    }
    return canActivate;
  }
}
