import { Injectable, UnauthorizedException } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt, Strategy } from "passport-jwt";
import { AppConfigService } from "../../../share/app-config.service";
import { User } from "../../../database/models/user.model";
import { UsersService } from "../../users/users.service";

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private appConfigService: AppConfigService,
    private usersService: UsersService
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: appConfigService.jwt().publicKey,
    });
  }

  async validate(args: {
    user: number;
    role: number;
    type: string;
  }): Promise<User> {
    if (args.type !== this.appConfigService.jwt().accessTokenType) {
      throw new UnauthorizedException();
    }

    const user = await this.usersService.findBy({
      id: args.user,
      roleId: args.role,
      active: true,
    });

    if (!user) {
      throw new UnauthorizedException();
    }

    return user;
  }
}
