import { makeAutoObservable } from "mobx";
import { mobxFetch } from "@shared";
import {
  TestingModeResponse,
  getTestingModeApi,
  setTestingModeApi,
} from "./api";

const POLLING_INTERVAL = 10_000;

class TestingModeStore {
  testingMode: TestingModeResponse | null = null;
  testingModeLoading = false;
  testingModeError: string | null = null;

  setTestingModeResult: TestingModeResponse | null = null;
  setTestingModeLoading = false;
  setTestingModeError: string | null = null;

  constructor() {
    makeAutoObservable(this);
  }

  get isEnabled(): boolean {
    return this.testingMode?.enabled ?? false;
  }

  fetchTestingModeAction = mobxFetch<TestingModeResponse, TestingModeStore>({
    store: this,
    value: "testingMode",
    loading: "testingModeLoading",
    error: "testingModeError",
    fn: getTestingModeApi,
    pollingInterval: POLLING_INTERVAL,
  });

  setTestingModeAction = mobxFetch<
    { enabled: boolean },
    TestingModeResponse,
    TestingModeStore
  >({
    store: this,
    value: "setTestingModeResult",
    loading: "setTestingModeLoading",
    error: "setTestingModeError",
    fn: setTestingModeApi,
    onSuccess: (result) => {
      this.testingMode = result;
    },
  });

  startPolling() {
    this.fetchTestingModeAction();
  }

  stopPolling() {
    this.fetchTestingModeAction.stopPolling?.();
  }
}

export const testingModeStore = new TestingModeStore();
export { TestingModeStore };
