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

export interface JwtPayload {
  // Identity-service uses 'userId' field
  userId: string
  accountSequence?: string
  deviceId?: string
  type?: string
  // Legacy support for 'sub' field
  sub?: string
  walletAddress?: string
  roles?: string[]
  iat?: number
  exp?: number
}

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private configService: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get<string>('JWT_SECRET'),
    })
  }

  async validate(payload: JwtPayload) {
    // Support both 'userId' (from identity-service) and 'sub' (legacy)
    const userId = payload.userId || payload.sub
    return {
      userId,
      accountSequence: payload.accountSequence,
      deviceId: payload.deviceId,
      walletAddress: payload.walletAddress,
      roles: payload.roles,
    }
  }
}
