import { Request } from 'express';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { jwtConstants } from '../../config/common';
import { UserService } from '../user/user.service';

interface SessionData {
  sessionIndex: string;
}

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private userService: UserService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: jwtConstants.secret,
      passReqToCallback: true,
    });
  }

  async validate(req: Request, payload: any) {
    // console.log(req.session);
    // console.log(payload.sessionId);
    if (
      (req.session as unknown as SessionData).sessionIndex !== payload.sessionId
    ) {
      //throw new UnauthorizedException('sessionIndex does not match');
    }

    const empId = req.query.empId;
    if (empId && empId != payload.sub) {
      throw new UnauthorizedException('empId does not match userId in token');
    }

    const user = await this.userService.findOne(payload.sub);
    if (!user) {
      throw new UnauthorizedException('Invalid User');
    }

    return {
      userId: payload.sub,
      username: payload.username,
      sessionId: payload.sessionId,
      activeRole: payload.activeRole,
    };
  }
}
