import { Injectable, Logger } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  private readonly logger = new Logger(JwtStrategy.name);

  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: process.env.JWT_SECRET,
    });
  }

  async validate(payload: { sub?: number; id?: number; userId?: number; username?: string; role?: string; isPremium?: boolean }) {
    const resolvedUserId = payload.sub ?? payload.id ?? payload.userId;
    this.logger.log(`Validating token for user ID: ${resolvedUserId}, Username: ${payload.username}`);
    return {
      id: resolvedUserId,
      userId: resolvedUserId,
      username: payload.username,
      role: payload.role ?? 'user',
      isPremium: payload.isPremium ?? false,
    };
  }
}
