'use strict';

var errors = require('@backstage/errors');
var state = require('./state.cjs.js');

class OAuthEnvironmentHandler {
  constructor(handlers) {
    this.handlers = handlers;
  }
  static mapConfig(config, factoryFunc) {
    const envs = config.keys();
    const handlers = /* @__PURE__ */ new Map();
    for (const env of envs) {
      const envConfig = config.getConfig(env);
      const handler = factoryFunc(envConfig);
      handlers.set(env, handler);
    }
    return new OAuthEnvironmentHandler(handlers);
  }
  async start(req, res) {
    const provider = this.getProviderForEnv(req);
    await provider.start(req, res);
  }
  async frameHandler(req, res) {
    const provider = this.getProviderForEnv(req);
    await provider.frameHandler(req, res);
  }
  async refresh(req, res) {
    const provider = this.getProviderForEnv(req);
    await provider.refresh?.(req, res);
  }
  async logout(req, res) {
    const provider = this.getProviderForEnv(req);
    await provider.logout?.(req, res);
  }
  getEnvFromRequest(req) {
    const reqEnv = req.query.env?.toString();
    if (reqEnv) {
      return reqEnv;
    }
    const stateParams = req.query.state?.toString();
    if (!stateParams) {
      return void 0;
    }
    const { env } = state.decodeOAuthState(stateParams);
    return env;
  }
  getProviderForEnv(req) {
    const env = this.getEnvFromRequest(req);
    if (!env) {
      throw new errors.InputError(`Must specify 'env' query to select environment`);
    }
    const handler = this.handlers.get(env);
    if (!handler) {
      throw new errors.NotFoundError(
        `No configuration available for the '${env}' environment of this provider.`
      );
    }
    return handler;
  }
}

exports.OAuthEnvironmentHandler = OAuthEnvironmentHandler;
//# sourceMappingURL=OAuthEnvironmentHandler.cjs.js.map
