import { defineStore } from "pinia";
import type {
  SetNewsletterConfigViewModel,
  NewsletterConfigViewModel,
} from "@/viewmodels/admin/settings/newsletterConfig.models";
import { http } from "@/serverCom";
import type { AxiosResponse } from "axios";

export const useNewsletterConfigStore = defineStore("newsletterConfi", {
  state: () => {
    return {
      config: [] as Array<NewsletterConfigViewModel>,
      loading: "loading" as "loading" | "fetched" | "failed",
    };
  },
  actions: {
    fetchNewsletterConfigs() {
      this.loading = "loading";
      http
        .get("/admin/newsletterconfig")
        .then((result) => {
          this.config = result.data;
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchNewsletterConfigById(id: number): Promise<AxiosResponse<any, any>> {
      return http.get(`/admin/newsletterconfig/${id}`);
    },
    async setNewsletterConfig(setConfig: SetNewsletterConfigViewModel): Promise<AxiosResponse<any, any>> {
      const result = await http.put(`/admin/newsletterconfig`, {
        comTypeId: setConfig.comTypeId,
        config: setConfig.config,
      });
      this.fetchNewsletterConfigs();
      return result;
    },
    async deleteNewsletterConfig(newsletterConfigStore: number): Promise<AxiosResponse<any, any>> {
      const result = await http.delete(`/admin/newsletterconfig/${newsletterConfigStore}`);
      this.fetchNewsletterConfigs();
      return result;
    },
  },
});
