import { InvalidationAction } from '@dvn/core/models/actions';
import { getCookieStorage } from '@dvn/kimlik/storage';
import { createMentornityApiInstance } from '../../../mentornity-js-client';
import { tableListViewOrganisationNewest, formViewOrganisationChangeDomain, detailViewOrganisation, tableListViewOrganisation, } from '../configs/view-configs';
import { mentornityApiEndpoint } from '../constants/env';
export class ChangeOrganisationDomainFormHandler {
  constructor() {
    const { jwt, sessionId } = getCookieStorage().getAll();
    this.api = createMentornityApiInstance(mentornityApiEndpoint, {
      'Authorization': `Bearer ${jwt}`,
      'Client': 'd2ViLWFkbWlu',
      'Session-Token': sessionId,
    });
  }
  onSubmit(event) {
    const { values: { domain, organisationId } } = event.detail;
    return new Promise((resolve, reject) => {
      this.api.changeOrganisationDomain({ domain, organisationId }).then(() => {
        resolve({
          events: [
            new InvalidationAction(formViewOrganisationChangeDomain.ID, detailViewOrganisation.ID),
            new InvalidationAction(formViewOrganisationChangeDomain.ID, tableListViewOrganisation.ID),
            new InvalidationAction(formViewOrganisationChangeDomain.ID, tableListViewOrganisationNewest.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']);
      });
    });
  }
}
