import { defineStore } from "pinia";
import type {
  CreateCommunicationTypeViewModel,
  UpdateCommunicationTypeViewModel,
  CommunicationTypeViewModel,
} from "@/viewmodels/admin/communicationType.models";
import { http } from "@/serverCom";
import type { AxiosResponse } from "axios";
import type { CommunicationFieldType } from "@/types/fieldTypes";

export const useCommunicationTypeStore = defineStore("communicationType", {
  state: () => {
    return {
      communicationTypes: [] as Array<CommunicationTypeViewModel>,
      availableFields: [] as Array<CommunicationFieldType>,
      loading: "loading" as "loading" | "fetched" | "failed",
      loadingFields: "loading" as "loading" | "fetched" | "failed",
    };
  },
  actions: {
    fetchCommunicationTypes() {
      this.loading = "loading";
      http
        .get("/admin/communicationType")
        .then((result) => {
          this.communicationTypes = result.data;
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchCommunicationTypeById(id: number): Promise<AxiosResponse<any, any>> {
      return http.get(`/admin/communicationType/${id}`);
    },
    fetchAvailableFields() {
      this.loadingFields = "loading";
      http
        .get("/admin/communicationType/fields")
        .then((result) => {
          this.availableFields = result.data;
          this.loadingFields = "fetched";
        })
        .catch((err) => {
          this.loadingFields = "failed";
        });
    },
    async createCommunicationType(
      communicationType: CreateCommunicationTypeViewModel
    ): Promise<AxiosResponse<any, any>> {
      const result = await http.post(`/admin/communicationType`, {
        communicationType: communicationType.type,
        fields: communicationType.fields,
      });
      this.fetchCommunicationTypes();
      return result;
    },
    async updateActiveCommunicationType(
      communicationType: UpdateCommunicationTypeViewModel
    ): Promise<AxiosResponse<any, any>> {
      const result = await http.patch(`/admin/communicationType/${communicationType.id}`, {
        communicationType: communicationType.type,
        fields: communicationType.fields,
      });
      this.fetchCommunicationTypes();
      return result;
    },
    async deleteCommunicationType(communicationType: number): Promise<AxiosResponse<any, any>> {
      const result = await http.delete(`/admin/communicationType/${communicationType}`);
      this.fetchCommunicationTypes();
      return result;
    },
  },
});
