import type * as FinGAP from 'Components/Calculation/Form/Insurance/FinGAPTable/types';
import type { IObservableArray } from 'mobx';
import { makeAutoObservable, observable } from 'mobx';
import type RootStore from 'stores/root';
import Validation from '../../validation';
import type { ValidationParams } from '../../validation/types';

export default class FinGAPTable {
  root: RootStore;
  validation: Validation;
  risks: IObservableArray<FinGAP.Risk>;
  selectedKeys: Set<string>;

  constructor(rootStore: RootStore) {
    this.selectedKeys = new Set();
    this.risks = observable<FinGAP.Risk>([]);

    this.validation = new Validation({
      err_key: 'ERR_FINGAP_TABLE',
      err_title: 'Таблица рисков Safe Finance',
    });

    makeAutoObservable(this);
    this.root = rootStore;
  }

  setRisks = (risks: FinGAP.Risk[]) => {
    this.risks.replace(risks);
  };

  setSelectedKeys = (keys: string[]) => {
    this.selectedKeys = new Set(keys);
  };

  get totalSum() {
    return this.risks
      .filter((risk) => this.selectedKeys.has(risk.key))
      .reduce((sum, risk) => sum + risk.premium, 0);
  }

  validate = ({ invalid, message }: ValidationParams) => {
    if (invalid) {
      this.validation?.addError(message);
    } else {
      this.validation?.removeError(message);
    }
  };

  clear = () => {
    this.risks.clear();
    this.selectedKeys.clear();
  };
}
