import { ExtractJwt, Strategy } from 'passport-jwt'
import { PassportStrategy } from '@nestjs/passport'
import { Inject, Injectable, Logger, UnauthorizedException } from '@nestjs/common'
import jwtconfig from './jwt.config'
import { ConfigType } from '@nestjs/config'
import { Redis } from 'ioredis'
import { UsersService } from '../users/users.service'
import { Role } from '../model/role.enum'

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
    private redis: Redis
    constructor(
        @Inject(jwtconfig.KEY)
        private readonly jwtConfiguration: ConfigType<typeof jwtconfig>,
        private readonly userService: UsersService
    ) {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
            ignoreExpiration: false,
            secretOrKey: jwtConfiguration.secret
        })
        this.redis = new Redis(process.env.REDIS_URI)
    }

    async validate(payload: any) {
        const user = await this.userService.findById(payload.sub)
        if (!user) {
            throw new UnauthorizedException('User not found')
        }
        if (!(payload.roles.includes(Role.Admin) || payload.roles.includes(Role.Api))) {
            if (!user.iat) {
                throw new UnauthorizedException('用户身份已过期，请重新登录')
            }
            if (payload.iat < user.iat) {
                //throw new UnauthorizedException('用户身份已过期，请重新登录')
            }
        }
        return {
            id: payload.sub,
            userId: payload.sub,
            username: payload.username,
            roles: payload.roles,
            orgId: user.orgId,
        }
    }
}
