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

import AdapterError from '@ember-data/adapter/error';
import { service } from '@ember/service';
import Component from '@ember/component';
import { computed } from '@ember/object';
import { task } from 'ember-concurrency';
import { waitFor } from '@ember/test-waiters';
import { capitalize } from '@ember/string';
import { singularize } from 'ember-inflector';

/**
 * @module GeneratedItem
 * The `GeneratedItem` component is the form to configure generated items related to mounts (e.g. groups, roles, users)
 *
 * @example
 * ```js
 * <GeneratedItem @model={{model}} @mode={{mode}} @itemType={{itemType/>
 * ```
 *
 * @property model=null {DS.Model} - The corresponding item model that is being configured.
 * @property mode {String} - which config mode to use. either `show`, `edit`, or `create`
 * @property itemType {String} - the type of item displayed
 *
 */

export default Component.extend({
  model: null,
  itemType: null,
  flashMessages: service(),
  router: service(),
  modelValidations: null,
  isFormInvalid: false,
  props: computed('model', function () {
    return this.model.serialize();
  }),

  get title() {
    const title = `${capitalize(this.mode)} ${singularize(this.itemType)}`;
    if (this.mode === 'show') {
      return this.model.id;
    } else if (this.mode === 'edit') {
      return `${title} ${this.model.id}`;
    }

    return `${capitalize(this.mode)} ${singularize(this.itemType)}`;
  },

  validateForm() {
    // Only validate on new models because blank passwords will not be updated
    // in practice this only happens for userpass users
    if (this.model.validate && this.model.isNew) {
      const { isValid, state } = this.model.validate();
      this.setProperties({
        modelValidations: state,
        isFormInvalid: !isValid,
      });
      return isValid;
    } else {
      this.set('isFormInvalid', false);
      return true;
    }
  },
  saveModel: task(
    waitFor(function* () {
      const isValid = this.validateForm();
      if (!isValid) {
        return;
      }
      try {
        yield this.model.save();
      } catch (err) {
        // AdapterErrors are handled by the error-message component
        // in the form
        if (err instanceof AdapterError === false) {
          throw err;
        }
        return;
      }
      this.router.transitionTo('vault.cluster.access.method.item.list').followRedirects();
      this.flashMessages.success(`Successfully saved ${this.itemType} ${this.model.id}.`);
    })
  ),
  init() {
    this._super(...arguments);
    if (this.mode === 'edit') {
      // For validation to work in edit mode,
      // reconstruct the model values from field group
      this.model.fieldGroups.forEach((element) => {
        if (element.default) {
          element.default.forEach((attr) => {
            const fieldValue = attr.options && attr.options.fieldValue;
            if (fieldValue) {
              this.model[attr.name] = this.model[fieldValue];
            }
          });
        }
      });
    }
  },
  actions: {
    onKeyUp(name, value) {
      this.model.set(name, value);
    },
    deleteItem() {
      this.model.destroyRecord().then(() => {
        this.router.transitionTo('vault.cluster.access.method.item.list').followRedirects();
        this.flashMessages.success(`Successfully deleted ${this.itemType} ${this.model.id}.`);
      });
    },
  },
});
