import { PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { Injectable, UnauthorizedException, Logger, Inject, Scope } from '@nestjs/common';
import { JwtPayload } from './jwt-payload.interface';
import * as config from 'config';
import { getConnection } from 'typeorm';
import { PcduserRepository } from './pcduser.repository';
import { PcduserDto } from 'src/auth/dto/pcd-user.dto';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {

    private logger = new Logger('Jwt Strategy'); // for logging

    constructor(
    ) {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
            ignoreExpiration: true,
            secretOrKey: process.env.JWT_SECRET || config.get('jwt').secret,
        })
    }

    async validate(payload: JwtPayload) {
        const { userId, userName, emailId, module } = payload;
        this.logger.log(`Payload ${JSON.stringify(payload)}`);
       
        let connect =  getConnection();
        const repo = await connect.getCustomRepository(PcduserRepository);
        const user:PcduserDto = await repo.findOne(userId);
        delete user.pass;
        delete user.salt;
        if (!user) {
            this.logger.log(` Unauthorized `);
            throw new UnauthorizedException();
        }

        user["payload"] = payload;

        return user;
    }

}