import { defineStore } from "pinia";
import type { CreateQueryViewModel, QueryViewModel, UpdateQueryViewModel } from "@/viewmodels/admin/settings/query.models";
import { http } from "@/serverCom";
import type { AxiosResponse } from "axios";
import { useQueryBuilderStore } from "../club/queryBuilder";
import { useModalStore } from "../../modal";
import { defineAsyncComponent, markRaw } from "vue";
import { useAbilityStore } from "../../ability";

export const useQueryStoreStore = defineStore("queryStore", {
  state: () => {
    return {
      queries: [] as Array<QueryViewModel>,
      loading: "loading" as "loading" | "fetched" | "failed",
    };
  },
  actions: {
    fetchQueries() {
      this.loading = "loading";
      http
        .get("/admin/querystore")
        .then((result) => {
          this.queries = result.data;
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchQueryById(id: number): Promise<AxiosResponse<any, any>> {
      return http.get(`/admin/querystore/${id}`);
    },
    triggerSave() {
      const queryBuilderStore = useQueryBuilderStore();
      const modalStore = useModalStore();
      const abilityStore = useAbilityStore();
      if (queryBuilderStore.activeQueryId != undefined && abilityStore.can("update", "settings", "query_store")) {
        modalStore.openModal(
          markRaw(
            defineAsyncComponent(() => import("@/components/admin/settings/queryStore/UpdateQueryStoreModal.vue"))
          ),
          queryBuilderStore.activeQueryId
        );
      } else {
        modalStore.openModal(
          markRaw(
            defineAsyncComponent(() => import("@/components/admin/settings/queryStore/CreateQueryStoreModal.vue"))
          )
        );
      }
    },
    async createQueryStore(query: CreateQueryViewModel): Promise<AxiosResponse<any, any>> {
      const result = await http.post(`/admin/querystore`, {
        query: query.query,
        title: query.title,
      });
      if (result.status == 200) {
        const queryBuilderStore = useQueryBuilderStore();
        queryBuilderStore.activeQueryId = result.data;
      }
      this.fetchQueries();
      return result;
    },
    async updateActiveQueryStore(query: UpdateQueryViewModel): Promise<AxiosResponse<any, any>> {
      const result = await http.patch(`/admin/querystore/${query.id}`, {
        query: query.query,
      });
      this.fetchQueries();
      return result;
    },
    async deleteQueryStore(queryStore: number): Promise<AxiosResponse<any, any>> {
      const result = await http.delete(`/admin/querystore/${queryStore}`);
      this.fetchQueries();
      return result;
    },
  },
});
