import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { InjectDataSource } from '@nestjs/typeorm';
import { JwtGuard as IamJwtGuard } from '@tria-plc/api-common/modules/auth/services/jwt.guard';
import { DataSource } from 'typeorm';

/**
 * Like the IAM JwtGuard, but never rejects the request.
 *
 * When a valid IAM bearer token is present, `request.user` is populated with
 * the package `TCurrentUser`. Missing or invalid tokens continue as guests.
 */
@Injectable()
export class OptionalJwtGuard extends IamJwtGuard implements CanActivate {
  constructor(
    reflector: Reflector,
    @InjectDataSource() dataSource: DataSource,
  ) {
    super(reflector, dataSource);
  }

  async canActivate(context: ExecutionContext): Promise<boolean> {
    try {
      await super.canActivate(context);
    } catch {
      context.switchToHttp().getRequest().user = undefined;
    }
    return true;
  }
}
