import { Injectable, UnauthorizedException } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt, Strategy } from "passport-jwt";
import { AccountRepo } from "src/modules/account/account.repo";

@Injectable()
export class JwtAccessStrategy extends PassportStrategy(Strategy, "access-token") {
  constructor(
    configService: ConfigService,
    private accountRepo: AccountRepo
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: configService.get<string>('JWT_SECRET')!
    });
  }

  async validate(payload: any) {
    console.log(payload);
    const user = await this.accountRepo.findById(payload.id);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}