import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { SYSTEM_USER_ID, UserDTO } from '../dto/user-dto';
import { ConfigService } from '@nestjs/config';
import { UserExtendedDTO } from '../dto/user-extended-dto';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor(private configService: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: !!configService.get('auth.jwtIgnoreExpiration'),
      secretOrKey: configService.get('auth.publicKey'),
      algorithms: ['RS256'],
    });
  }

  async validate(payload: any): Promise<UserDTO> {
    if (payload.id === SYSTEM_USER_ID) {
      throw new UnauthorizedException('Cannot use that user');
    }

    const jwt_token = new UserExtendedDTO();
    jwt_token.id = payload.id;
    jwt_token.email = payload.email.toLowerCase();
    jwt_token.licenses = payload.licenses;
    jwt_token.name = payload.name;
    return jwt_token;
  }
}
