import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import * as fs from 'fs';
import { JwtPayload } from '../../../common/decorators/current-user.decorator';

/**
 * JwtStrategy - Passport-Strategy fuer RS256 JWT-Validierung.
 *
 * Extrahiert den Token aus dem Authorization-Header (Bearer Token).
 * Validiert Signatur (RS256), Issuer und Expiration automatisch.
 */
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(config: ConfigService) {
    const publicKeyPath = config.get<string>(
      'JWT_PUBLIC_KEY_PATH',
      '/app/keys/jwt-public.pem',
    );

    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: fs.readFileSync(publicKeyPath, 'utf8'),
      algorithms: ['RS256'],
      issuer: config.get<string>('JWT_ISSUER', 'insight-platform'),
    });
  }

  /**
   * Wird nach erfolgreicher JWT-Validierung aufgerufen.
   * Der Return-Wert landet in request.user.
   */
  validate(payload: JwtPayload): JwtPayload {
    return {
      sub: payload.sub,
      email: payload.email,
      role: payload.role,
      tenantId: payload.tenantId,
      tenantSlug: payload.tenantSlug,
      jti: payload.jti,
      iat: payload.iat,
      exp: payload.exp,
    };
  }
}
