import { pipe } from 'fp-ts/function';
import * as O from 'fp-ts/Option';
import { getOrError } from '../../../../utils';
import { withMinimalDuration } from '../../../../utils/promise';
import userApi from '../../apis/user-api/user.api';
import { UserProfileDto } from '../../apis/user-api/user-api.dto';
import roleManagementApi from './api/role-management.api';
import roleManagementQuery from './store/role-management.query';
import roleManagementStore from './store/role-management.store';
export class RoleManagementService {
  async getBasicProfileByEmail(email) {
    const res = await userApi.getBasicProfileByEmail(email);
    return pipe(res, O.map((dto) => dto));
  }
  async getEditorProfiles() {
    const editorProfiles = (await roleManagementApi.getEditorProfiles()).map(UserProfileDto.toDomain);
    roleManagementStore.update((state) => {
      state.editorProfiles = editorProfiles;
    });
  }
  async removeSelectedEditor() {
    roleManagementStore.showRemoveEditorDialog(false);
    roleManagementStore.setEditorLoading(true);
    const editor = getOrError(roleManagementQuery.getValue().selectedEditor);
    await roleManagementApi.assignRole(editor.basicProfile.profileId, 'user');
    await this.getEditorProfiles();
    roleManagementStore.setEditorLoading(false);
  }
  showRemoveEditorDialog(editorProfile) {
    roleManagementStore.selectEditor(editorProfile);
    roleManagementStore.showRemoveEditorDialog(true);
  }
  async addEditorByEmail(email) {
    roleManagementStore.setEditorLoading(true);
    const user = await withMinimalDuration(this.getBasicProfileByEmail(email), 300);
    if (O.isSome(user)) {
      await roleManagementApi.assignRole(user.value.profileId, 'accountEditor');
      await this.getEditorProfiles();
    }
    roleManagementStore.setEditorLoading(false);
    return user;
  }
}
export default new RoleManagementService();
