import { defineStore } from "pinia";
import type {
  CreateQualificationViewModel,
  UpdateQualificationViewModel,
  QualificationViewModel,
} from "@/viewmodels/admin/settings/qualification.models";
import { http } from "@/serverCom";
import type { AxiosResponse } from "axios";

export const useQualificationStore = defineStore("qualification", {
  state: () => {
    return {
      qualifications: [] as Array<QualificationViewModel>,
      loading: "loading" as "loading" | "fetched" | "failed",
    };
  },
  actions: {
    fetchQualifications() {
      this.loading = "loading";
      http
        .get("/admin/qualification")
        .then((result) => {
          this.qualifications = result.data;
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchQualificationById(id: number): Promise<AxiosResponse<any, any>> {
      return http.get(`/admin/qualification/${id}`);
    },
    async createQualification(qualification: CreateQualificationViewModel): Promise<AxiosResponse<any, any>> {
      const result = await http.post(`/admin/qualification`, {
        qualification: qualification.qualification,
        description: qualification.description,
      });
      this.fetchQualifications();
      return result;
    },
    async updateActiveQualification(qualification: UpdateQualificationViewModel): Promise<AxiosResponse<any, any>> {
      const result = await http.patch(`/admin/qualification/${qualification.id}`, {
        qualification: qualification.qualification,
        description: qualification.description,
      });
      this.fetchQualifications();
      return result;
    },
    async deleteQualification(qualification: number): Promise<AxiosResponse<any, any>> {
      const result = await http.delete(`/admin/qualification/${qualification}`);
      this.fetchQualifications();
      return result;
    },
  },
});
