import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import Strategy from 'passport-headerapikey';

@Injectable()
export class HeaderApiKeyStrategy extends PassportStrategy(
  Strategy,
  'api-key',
) {
  constructor(private readonly configService: ConfigService) {
    super(
      { header: 'x-api-key', prefix: '' },
      true,
      async (apiKey: string, done: any) => {
        return this.validate(apiKey, done);
      },
    );
  }

  public validate = (
    apiKey: string,
    done: (error: Error, data: any) => any,
  ) => {
    if (this.configService.get<string>('externalApiKey') === apiKey) {
      done(null, true);
    }

    done(new UnauthorizedException(), null);
  };
}
