import { defineStore } from "pinia";
import type { CreateMemberViewModel, UpdateMemberViewModel } from "@/viewmodels/admin/member.models";
import { http } from "@/serverCom";
import type { AxiosResponse } from "axios";
import type { MemberViewModel } from "@/viewmodels/admin/member.models";
import { useMemberStore } from "./member";
import type {
  CreateMemberQualificationViewModel,
  MemberQualificationViewModel,
  UpdateMemberQualificationViewModel,
} from "@/viewmodels/admin/memberQualification.models";

export const useMemberQualificationStore = defineStore("memberQualification", {
  state: () => {
    return {
      memberQualifications: [] as Array<MemberQualificationViewModel>,
      loading: "loading" as "loading" | "fetched" | "failed",
    };
  },
  actions: {
    fetchMemberQualificationsForMember() {
      const memberId = useMemberStore().activeMember;
      this.loading = "loading";
      http
        .get(`/admin/member/${memberId}/qualifications`)
        .then((result) => {
          this.memberQualifications = result.data;
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchMemberQualificationById(id: number) {
      const memberId = useMemberStore().activeMember;
      return http.get(`/admin/member/${memberId}/qualification/${id}`);
    },
    async createMemberQualification(
      memberQualification: CreateMemberQualificationViewModel
    ): Promise<AxiosResponse<any, any>> {
      const memberId = useMemberStore().activeMember;
      const result = await http.post(`/admin/member/${memberId}/qualification`, {
        note: memberQualification.note,
        start: memberQualification.start,
        qualificationId: memberQualification.qualificationId,
      });
      this.fetchMemberQualificationsForMember();
      return result;
    },
    async updateMemberQualification(
      memberQualification: UpdateMemberQualificationViewModel
    ): Promise<AxiosResponse<any, any>> {
      const memberId = useMemberStore().activeMember;
      const result = await http.patch(`/admin/member/${memberId}/qualification/${memberQualification.id}`, {
        note: memberQualification.note,
        start: memberQualification.start,
        end: memberQualification.end,
        terminationReason: memberQualification.terminationReason,
        qualificationId: memberQualification.qualificationId,
      });
      this.fetchMemberQualificationsForMember();
      return result;
    },
    async deleteMemberQualification(memberQualification: number): Promise<AxiosResponse<any, any>> {
      const memberId = useMemberStore().activeMember;
      const result = await http.delete(`/admin/member/${memberId}/qualification/${memberQualification}`);
      this.fetchMemberQualificationsForMember();
      return result;
    },
  },
});
