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

export const useNewsletterRecipientsStore = defineStore("newsletterRecipients", {
  state: () => {
    return {
      initialized: false as boolean,
      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.initialized = true;
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchNewsletterRecipientsPromise() {
      const newsletterId = useNewsletterStore().activeNewsletter;
      return http.get(`/admin/newsletter/${newsletterId}/recipients`);
    },
    async synchronizeActiveNewsletterRecipients() {
      if (!this.initialized) return;

      this.syncingNewsletterRecipients = "syncing";
      const newsletterId = useNewsletterStore().activeNewsletter;

      await http
        .patch(`/admin/newsletter/${newsletterId}/synchronize/recipients`, {
          recipients: 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) => {});
    },
  },
});
