import { defineStore } from "pinia";
import type {
  CreateExecutivePositionViewModel,
  UpdateExecutivePositionViewModel,
  ExecutivePositionViewModel,
} from "@/viewmodels/admin/settings/executivePosition.models";
import { http } from "@/serverCom";
import type { AxiosResponse } from "axios";

export const useExecutivePositionStore = defineStore("executivePosition", {
  state: () => {
    return {
      executivePositions: [] as Array<ExecutivePositionViewModel>,
      loading: "loading" as "loading" | "fetched" | "failed",
    };
  },
  actions: {
    fetchExecutivePositions() {
      this.loading = "loading";
      http
        .get("/admin/executivePosition")
        .then((result) => {
          this.executivePositions = result.data;
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchExecutivePositionById(id: number): Promise<AxiosResponse<any, any>> {
      return http.get(`/admin/executivePosition/${id}`);
    },
    async createExecutivePosition(executivePosition: CreateExecutivePositionViewModel) {
      const result = await http.post(`/admin/executivePosition`, {
        executivePosition: executivePosition.position,
      });
      this.fetchExecutivePositions();
      return result;
    },
    async updateActiveExecutivePosition(
      executivePosition: UpdateExecutivePositionViewModel
    ): Promise<AxiosResponse<any, any>> {
      const result = await http.patch(`/admin/executivePosition/${executivePosition.id}`, {
        executivePosition: executivePosition.position,
      });
      this.fetchExecutivePositions();
      return result;
    },
    async deleteExecutivePosition(executivePosition: number) {
      const result = await http.delete(`/admin/executivePosition/${executivePosition}`);
      this.fetchExecutivePositions();
      return result;
    },
  },
});
