// Generic, fully-configurable OAuth2 / OIDC provider for custom IdPs (Authentik,
// Keycloak, Okta, Azure AD, Zitadel, …). Unlike the built-ins, its endpoints and
// scopes come from the stored config. Profile mapping follows OIDC conventions
// with sensible fallbacks for plain OAuth2 userinfo shapes.

const OAuth2Provider = require('./oauth2.provider')

class GenericOidcProvider extends OAuth2Provider {
  constructor(config = {}) {
    super({ kind: config.kind || 'oidc', ...config })
    this.authorizeUrl = config.authorizeUrl ?? config.authorize_url ?? null
    this.tokenUrl = config.tokenUrl ?? config.token_url ?? null
    this.userinfoUrl = config.userinfoUrl ?? config.userinfo_url ?? null
    this.scopes = config.scopes || 'openid email profile'
  }

  authEndpoint() {
    return this.authorizeUrl
  }
  tokenEndpoint() {
    return this.tokenUrl
  }
  userinfoEndpoint() {
    return this.userinfoUrl
  }
  scopeString() {
    return this.scopes
  }
  normalizeProfile(p = {}) {
    return {
      subject: p.sub || p.id || p.user_id || p.uid || null,
      email: p.email || null,
      name: p.name || p.preferred_username || p.username || p.email || null,
    }
  }
}

module.exports = GenericOidcProvider
