import { defineStore } from "pinia";
import type {
  CreateCalendarTypeViewModel,
  UpdateCalendarTypeViewModel,
  CalendarTypeViewModel,
} from "@/viewmodels/admin/settings/calendarType.models";
import { http } from "@/serverCom";
import type { AxiosResponse } from "axios";

export const useCalendarTypeStore = defineStore("calendarType", {
  state: () => {
    return {
      calendarTypes: [] as Array<CalendarTypeViewModel>,
      loading: "loading" as "loading" | "fetched" | "failed",
      loadingFields: "loading" as "loading" | "fetched" | "failed",
    };
  },
  actions: {
    fetchCalendarTypes() {
      this.loading = "loading";
      http
        .get("/admin/calendartype")
        .then((result) => {
          this.calendarTypes = result.data;
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchCalendarTypeById(id: number): Promise<AxiosResponse<any, any>> {
      return http.get(`/admin/calendartype/${id}`);
    },
    async createCalendarType(calendarType: CreateCalendarTypeViewModel): Promise<AxiosResponse<any, any>> {
      const result = await http.post(`/admin/calendartype`, {
        type: calendarType.type,
        nscdr: calendarType.nscdr,
        color: calendarType.color,
        passphrase: calendarType.passphrase,
      });
      this.fetchCalendarTypes();
      return result;
    },
    async updateActiveCalendarType(calendarType: UpdateCalendarTypeViewModel): Promise<AxiosResponse<any, any>> {
      const result = await http.patch(`/admin/calendartype/${calendarType.id}`, {
        type: calendarType.type,
        nscdr: calendarType.nscdr,
        color: calendarType.color,
        passphrase: calendarType.passphrase,
      });
      this.fetchCalendarTypes();
      return result;
    },
    async deleteCalendarType(calendarType: number): Promise<AxiosResponse<any, any>> {
      const result = await http.delete(`/admin/calendartype/${calendarType}`);
      this.fetchCalendarTypes();
      return result;
    },
  },
});
