// a secret bundle is a set of secrets ready to be used in a project.
// it bundles secretgroups
import { SecretGroup } from './classes.secretgroup.js';
import * as plugins from '../plugins.js';

@plugins.smartdata.Manager()
export class SecretBundle extends plugins.smartdata.SmartDataDbDoc<
  SecretBundle,
  plugins.servezoneInterfaces.data.ISecretBundle
> {
  // STATIC

  // INSTANCE
  @plugins.smartdata.unI()
  public id: string;

  @plugins.smartdata.svDb()
  public data: plugins.servezoneInterfaces.data.ISecretBundle['data'];

  public async getSecretGroups() {
    const secretGroups: SecretGroup[] = [];
    for (const secretGroupId of this.data.includedSecretGroupIds) {
      secretGroups.push(
        await SecretGroup.getInstance({
          id: secretGroupId,
        }),
      );
    }
    return secretGroups;
  }

  /**
   * searches the secretGroups for environments and returns them
   */
  public async getEnvironments() {
    const environments = new Set();
    const secretGroups = await this.getSecretGroups();
    for (const secretGroup of secretGroups) {
      environments.add(secretGroup.data.environments);
    }
    return Array.from(environments);
  }

  public async getAuthorizationFromAuthKey(authKeyArg: string) {
    const authorization = this.data.authorizations.find((authArg) => {
      return authArg.secretAccessKey === authKeyArg;
    });
    return authorization;
  }

  public async getKeyValueObjectForEnvironment(environmentArg: string) {
    const secretGroups = await this.getSecretGroups();
    const returnObject = {};
    for (const secretGroup of secretGroups) {
      if (!secretGroup.data.environments[environmentArg]) {
        continue;
      }
      returnObject[secretGroup.data.key] = secretGroup.data.environments[environmentArg].value;
    }
    return returnObject;
  }
}