import { ApiDefinitions, IOidcAuthorization, IRequestAuthorization, RequestAuthorizationKind } from "@api-client/core/build/browser.js";
import { PropertyValues } from "lit";
import { property } from "lit/decorators.js";
import OidcAuthorization from "../../authorization/ui/OidcAuthorization.js";

export default class AmfOidc extends OidcAuthorization {
  /**
   * The in-memory key where the values are stored.
   */
  @property({ type: Object }) security?: ApiDefinitions.IApiParametrizedSecurityScheme;

  protected override willUpdate(cp: PropertyValues<this>): void {
    if (cp.has('security')) {
      this.restoreValues();
    }
    super.willUpdate(cp);
  }

  protected ensureConfig(): IRequestAuthorization {
    if (!this.authorization) {
      this.authorization = {
        enabled: true,
        kind: RequestAuthorizationKind,
        type: 'oauth 2',
        valid: false,
        config: {
        } as IOidcAuthorization,
      };
    }
    return this.authorization;
  }

  protected restoreValues(): void {
    const { security } = this;
    this.authorization = undefined;
    const auth = this.ensureConfig();

    if (!security) {
      return;
    }

    const { scheme } = security;
    if (!scheme) {
      return;
    }
    const settings = scheme.settings as ApiDefinitions.IApiSecurityOpenIdConnectSettings | undefined;
    if (!settings) {
      return;
    }
    const { url } = settings;
    const cnf = auth.config as IOidcAuthorization;
    cnf.issuerUri = url;
    if (url) {
      this.discover();
    }
    auth.config = this.serialize();
    this.notifyChange();
  }
}
