import { some } from 'fp-ts/lib/Option';
import manageBenefitsApi from './api/manage-benefits.api';
import { ManageBenefitsPageStateDto } from './api/manage-benefits-api.dto';
import manageBenefitsStore from './store/manage-benefits.store';
export class ManageBenefitsService {
  async loadPageStateAsync() {
    manageBenefitsStore.setLoading(true);
    const pageStateDto = await manageBenefitsApi.getPageStateAsync();
    manageBenefitsStore.update((state) => {
      state.manageBenefitsPageState = ManageBenefitsPageStateDto.toDomain(pageStateDto);
    });
    manageBenefitsStore.setLoading(false);
  }
  async enableBenefitAsync(id) {
    await manageBenefitsApi.postCommandAsync(some(id), 'enableAccountBenefit');
    manageBenefitsStore.update((state) => {
      const targetBenefitIndex = state.manageBenefitsPageState.disabledBenefits.findIndex((benefit) => benefit.id === id);
      if (targetBenefitIndex === -1)
        return;
      const targetBenefit = state.manageBenefitsPageState.disabledBenefits.splice(targetBenefitIndex, 1)[0];
      targetBenefit.visibility.isEnabled = true;
      state.manageBenefitsPageState.enabledBenefits.push(targetBenefit);
    });
  }
  async disableBenefitAsync(id) {
    await manageBenefitsApi.postCommandAsync(some(id), 'disableAccountBenefit');
    manageBenefitsStore.update((state) => {
      const targetBenefitIndex = state.manageBenefitsPageState.enabledBenefits.findIndex((benefit) => benefit.id === id);
      if (targetBenefitIndex === -1)
        return;
      const targetBenefit = state.manageBenefitsPageState.enabledBenefits.splice(targetBenefitIndex, 1)[0];
      targetBenefit.visibility.isEnabled = false;
      state.manageBenefitsPageState.disabledBenefits.push(targetBenefit);
    });
  }
}
export default new ManageBenefitsService();
