import { Injectable, Logger, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { RedisClientService } from '../../cache/cache.service';
import { AppConfigService } from '../../config/app/app-config.service';
import { AuthPayload, RefreshTokenPayload } from '../decorators/auth.payload';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
  private readonly logger = new Logger(JwtStrategy.name);
  constructor(
    private readonly configService: AppConfigService,
    private readonly redisService: RedisClientService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.jwtAccessSecret,
    });
  }

  async validate(payload: RefreshTokenPayload): Promise<AuthPayload> {
    const { id, tid, prefix } = payload;
    const { isMark } = await this.redisService.checkMarkLogin(id, tid, prefix);
    // console.log(payload);

    if (!isMark) {
      this.logger.debug(
        `token in black list tid: ${tid}, sub: ${id}, prefix: ${prefix}`,
      );
      throw new UnauthorizedException('Token is in blacklist');
    }

    return {
      id: payload.id,
      // tid: payload.tid,
      account: payload.account,
      type: payload.type,
      containsPassword: payload.containsPassword,
    };
  }
}
