/**
 * Copyright IBM Corp. 2016, 2025
 * SPDX-License-Identifier: BUSL-1.1
 */

import Component from '@glimmer/component';
import { action } from '@ember/object';

import type PkiRoleForm from 'vault/forms/secrets/pki/role';
import type PkiConfigGenerateForm from 'vault/forms/secrets/pki/config/generate';
import type PkiKeyForm from 'vault/forms/secrets/pki/key';
import type { HTMLElementEvent } from 'forms';
/**
 * @module PkiKeyParameters
 * PkiKeyParameters components are used to display a list of key bit options depending on the selected key type. The key bits field is disabled until a key type is selected.
 * If the component renders in a group, other attrs may be passed in and will be rendered using the <FormField> component
 *
 * @param {class} model - The pki/role, pki/action, pki/key model.
 * @param {string} fields - Array of attributes from a formFieldGroup generated by the @withFormFields decorator ex: [{ name: 'attrName', type: 'string', options: {...} }]
 */
interface Args {
  form: PkiRoleForm | PkiKeyForm | PkiConfigGenerateForm;
}
interface TypeOptions {
  rsa: string;
  ec: string;
  ed25519: string;
  any: string;
}
interface BitOptions {
  [key: string]: Array<number>;
}

// first value in array is the default bits for that key type
const KEY_BITS_OPTIONS: BitOptions = {
  rsa: [2048, 3072, 4096, 0],
  ec: [256, 224, 384, 521, 0],
  ed25519: [0],
  any: [0],
};

export default class PkiKeyParameters extends Component<Args> {
  get keyBitOptions() {
    const keyType = this.args.form.data.key_type as keyof typeof KEY_BITS_OPTIONS;
    return keyType ? KEY_BITS_OPTIONS[keyType] : [];
  }

  @action
  handleSelection(name: string, selection: string) {
    this.args.form.set(name, selection);

    if (name === 'key_type' && Object.keys(KEY_BITS_OPTIONS)?.includes(selection)) {
      const bitOptions = KEY_BITS_OPTIONS[selection as keyof TypeOptions];
      if (bitOptions) {
        this.args.form.data.key_bits = bitOptions[0];
      }
    }
  }

  @action onKeyBitsChange(event: HTMLElementEvent<HTMLInputElement>) {
    this.handleSelection(event.target.name, event.target.value);
  }
}
