import { defineStore } from "pinia";
import type {
  CreateCalendarViewModel,
  UpdateCalendarViewModel,
  CalendarViewModel,
} from "@/viewmodels/admin/club/calendar.models";
import { http } from "@/serverCom";
import type { AxiosResponse } from "axios";

export const useCalendarStore = defineStore("calendar", {
  state: () => {
    return {
      calendars: [] as Array<CalendarViewModel>,
      loading: "loading" as "loading" | "fetched" | "failed",
      loadingFields: "loading" as "loading" | "fetched" | "failed",
    };
  },
  getters: {
    formattedItems: (state) => {
      return state.calendars.map((c) => ({
        id: c.id,
        title: c.title,
        start: c.starttime,
        end: c.endtime,
        backgroundColor: c.type.color,
      }));
    },
  },
  actions: {
    fetchCalendars() {
      this.loading = "loading";
      http
        .get("/admin/calendar")
        .then((result) => {
          this.calendars = result.data;
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchCalendarById(id: string): Promise<AxiosResponse<any, any>> {
      return http.get(`/admin/calendar/${id}`);
    },
    async createCalendar(calendar: CreateCalendarViewModel): Promise<AxiosResponse<any, any>> {
      const result = await http.post(`/admin/calendar`, {
        starttime: calendar.starttime,
        endtime: calendar.endtime,
        title: calendar.title,
        content: calendar.content,
        allDay: calendar.allDay,
        location: calendar.location,
        typeId: calendar.typeId,
      });
      this.fetchCalendars();
      return result;
    },
    async updateCalendar(calendar: UpdateCalendarViewModel): Promise<AxiosResponse<any, any>> {
      const result = await http.patch(`/admin/calendar/${calendar.id}`, {
        starttime: calendar.starttime,
        endtime: calendar.endtime,
        title: calendar.title,
        content: calendar.content,
        allDay: calendar.allDay,
        location: calendar.location,
        typeId: calendar.typeId,
      });
      this.fetchCalendars();
      return result;
    },
    async deleteCalendar(calendar: number): Promise<AxiosResponse<any, any>> {
      const result = await http.delete(`/admin/calendar/${calendar}`);
      this.fetchCalendars();
      return result;
    },
  },
});