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

/**
 * Shape of the JWT we issue.
 *
 * `sub` is the user ID as a string (bigints are serialized to strings in JSON).
 */
export interface JwtPayload {
  sub: string;
  username: string;
}

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(config: ConfigService) {
    const secret = config.get<string>('JWT_SECRET');
    if (!secret) {
      throw new Error('JWT_SECRET is not configured');
    }
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: secret,
    });
  }

  /**
   * Runs on every authenticated request. The returned object becomes
   * `request.user` for downstream controllers.
   */
  validate(payload: JwtPayload): { id: bigint; username: string } {
    if (!payload?.sub || !payload.username) {
      throw new UnauthorizedException('Invalid token payload');
    }
    return { id: BigInt(payload.sub), username: payload.username };
  }
}
