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

import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { service } from '@ember/service';
import { task } from 'ember-concurrency';
import { waitFor } from '@ember/test-waiters';
import errorMessage from 'vault/utils/error-message';

import type LdapLibraryModel from 'vault/models/ldap/library';
import { Breadcrumb, ValidationMap } from 'vault/vault/app-types';
import type FlashMessageService from 'vault/services/flash-messages';
import type RouterService from '@ember/routing/router-service';

interface Args {
  model: LdapLibraryModel;
  breadcrumbs: Array<Breadcrumb>;
}

export default class LdapCreateAndEditLibraryPageComponent extends Component<Args> {
  @service declare readonly flashMessages: FlashMessageService;
  @service('app-router') declare readonly router: RouterService;

  @tracked modelValidations: ValidationMap | null = null;
  @tracked invalidFormMessage = '';
  @tracked error = '';

  @task
  @waitFor
  *save(event: Event) {
    event.preventDefault();

    const { model } = this.args;
    const { isValid, state, invalidFormMessage } = model.validate();

    this.modelValidations = isValid ? null : state;
    this.invalidFormMessage = isValid ? '' : invalidFormMessage;

    if (isValid) {
      try {
        const action = model.isNew ? 'created' : 'updated';
        yield model.save();
        this.flashMessages.success(`Successfully ${action} the library ${model.name}.`);
        const libraryParam = model.completeLibraryName.includes('/')
          ? encodeURIComponent(model.completeLibraryName)
          : model.name;
        this.router.transitionTo(
          'vault.cluster.secrets.backend.ldap.libraries.library.details',
          libraryParam
        );
      } catch (error) {
        this.error = errorMessage(error, 'Error saving library. Please try again or contact support.');
      }
    }
  }

  @action
  cancel() {
    this.args.model.rollbackAttributes();
    this.router.transitionTo('vault.cluster.secrets.backend.ldap.libraries');
  }
}
