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

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    const secret = process.env.JWT_SECRET;
    if (!secret && process.env.NODE_ENV === 'production') {
      throw new Error('JWT_SECRET must be set in production');
    }
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: secret || 'dev_jwt_secret',
    });
  }

  async validate(payload: any) {
    if (!payload?.sub) throw new UnauthorizedException();
    // Permissions are re-checked against the database by PermissionsGuard;
    // the claim here is only a hint for cheap short-circuiting.
    return { id: Number(payload.sub), email: payload.email, permissions: payload.permissions };
  }
}
