import { InvalidationAction } from '@dvn/core/models/actions';
import { getCookieStorage } from '@dvn/kimlik/storage';
import { createMentornityApiInstance } from '../../../mentornity-js-client';
import { formViewOrganisationCreate, tableListViewOrganisation, } from '../configs/view-configs';
import { mentornityApiEndpoint } from '../constants/env';
export class CreateOrganisationFormHandler {
  constructor() {
    const { jwt, sessionId } = getCookieStorage().getAll();
    this.api = createMentornityApiInstance(mentornityApiEndpoint, {
      'Authorization': `Bearer ${jwt}`,
      'Client': 'd2ViLWFkbWlu',
      'Session-Token': sessionId,
    });
  }
  onSubmit(event) {
    const { values: { admin, sourceOrganisationId, newOrganisationDomain, newOrganisationTitle, timeZone, } } = event.detail;
    return new Promise((resolve, reject) => {
      this.api.cloneOrganisation({
        sourceOrganisationId,
        newOrganisationDomain,
        newOrganisationTitle,
        adminIds: [admin],
        timeZone,
      }).then(() => {
        resolve({
          events: [
            new InvalidationAction(formViewOrganisationCreate.ID, tableListViewOrganisation.ID),
          ],
          navigation: {
            type: 'navigation',
            direction: 'back'
          }
        });
      }).catch(error => {
        if (error.data && error.data.message === 'domain-already-exists') {
          reject(['Domain is already used by another program.']);
          return;
        }
        reject(['Unexpected error']);
      });
    });
  }
}
