import { action, makeObservable, observable } from 'mobx';
import { loadable } from './Decorators/LoadingDecorator';
import { EntityStore } from './EntityStore';
import { Account } from './AccountsStore';
import { RootStore } from './RootStore';
import { ISettingsAuth, ISettingsTls } from 'types/default';
import request from 'services/request';
import { environment } from '../enviroments/enviroments';

export class SettingsStore extends EntityStore<Account> {
  constructor(private readonly rootStore: RootStore) {
    super();
    makeObservable(this);
  }

  @observable settingsAuth: ISettingsAuth | null = null;

  @observable settingsTls: ISettingsTls | null = null;

  @loadable getSettingsAuth(): void {
    request({
      method: 'get',
      url: `${environment.settings.auth}`,
    }).then(
      action((response: any) => {
        this.settingsAuth = response.data;
      }),
    );
  }

  @loadable async getSettingsTls(): Promise<void> {
    await request({
      method: 'get',
      url: `${environment.settings.tls}`,
    }).then(
      action((response: any) => {
        this.settingsTls = response.data;
      }),
    );
  }

  @action async postSettingsTls(): Promise<void> {
    await request({
      method: 'post',
      url: `${environment.settings.tls}`,
    }).then(
      action((response: any) => {
        this.settingsTls = response.data;
      }),
    );
  }

  @action async deleteCertificates(): Promise<void> {
    await request({
      method: 'delete',
      url: `${environment.settings.tls}`,
    }).then(
      action(() => {
        this.settingsTls = null;
      }),
    );
  }

  @action async patchSettingsTls(data: ISettingsTls): Promise<void> {
    await request({
      method: 'put',
      url: `${environment.settings.tls}`,
      headers: {
        'Content-Type':
          'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW',
      },
      data,
    }).then(
      action((response: any) => {
        this.settingsTls = response.data;
      }),
    );
  }

  @action async patchSettingsAuth(data: ISettingsAuth): Promise<void> {
    await request({
      method: 'patch',
      url: `${environment.settings.auth}`,
      data,
    }).then(
      action((response: any) => {
        this.settingsAuth = response.data;
      }),
    );
  }
}
