import { defineStore } from "pinia";
import { http } from "@/serverCom";
import type {
  NewsletterRecipientsViewModel,
  SyncNewsletterRecipientsViewModel,
} from "@/viewmodels/admin/newsletterRecipients.models";
import { useProtocolStore } from "./protocol";
import cloneDeep from "lodash.clonedeep";
import isEqual from "lodash.isequal";

export const useNewsletterRecipientsStore = defineStore("newsletterRecipients", {
  state: () => {
    return {
      recipients: [] as Array<number>,
      origin: [] as Array<number>,
      loading: "loading" as "loading" | "fetched" | "failed",
      syncingNewsletterRecipients: "synced" as "synced" | "syncing" | "detectedChanges" | "failed",
    };
  },
  getters: {
    detectedChangeNewsletterRecipients: (state) =>
      !isEqual(state.origin, state.recipients) && state.syncingNewsletterRecipients != "syncing",
  },
  actions: {
    setNewsletterRecipientsSyncingState(state: "synced" | "syncing" | "detectedChanges" | "failed") {
      this.syncingNewsletterRecipients = state;
    },
    fetchNewsletterRecipients() {
      this.loading = "loading";
      this.fetchNewsletterRecipientsPromise()
        .then((result) => {
          this.origin = result.data.map((d: NewsletterRecipientsViewModel) => d.memberId);
          this.recipients = cloneDeep(this.origin);
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchNewsletterRecipientsPromise() {
      const protocolId = useProtocolStore().activeProtocol;
      return http.get(`/admin/protocol/${protocolId}/presence`);
    },
    async synchronizeActiveNewsletterRecipients() {
      this.syncingNewsletterRecipients = "syncing";
      const protocolId = useProtocolStore().activeProtocol;
      await http
        .put(`/admin/protocol/${protocolId}/synchronize/presence`, {
          presence: this.recipients,
        })
        .then((res) => {
          this.syncingNewsletterRecipients = "synced";
        })
        .catch((err) => {
          this.syncingNewsletterRecipients = "failed";
        });
      this.fetchNewsletterRecipientsPromise()
        .then((result) => {
          this.origin = result.data.map((d: NewsletterRecipientsViewModel) => d.memberId);
          if (this.detectedChangeNewsletterRecipients) this.syncingNewsletterRecipients = "detectedChanges";
        })
        .catch((err) => {});
    },
  },
});