import { defineStore } from "pinia";
import type { CreateMemberViewModel, UpdateMemberViewModel } from "@/viewmodels/admin/club/member/member.models";
import { http } from "@/serverCom";
import type { AxiosResponse } from "axios";
import type { MemberViewModel } from "@/viewmodels/admin/club/member/member.models";
import { useMemberStore } from "./member";
import type {
  CreateMemberExecutivePositionViewModel,
  MemberExecutivePositionViewModel,
  UpdateMemberExecutivePositionViewModel,
} from "@/viewmodels/admin/club/member/memberExecutivePosition.models";

export const useMemberExecutivePositionStore = defineStore("memberExecutivePosition", {
  state: () => {
    return {
      memberExecutivePositions: [] as Array<MemberExecutivePositionViewModel>,
      loading: "loading" as "loading" | "fetched" | "failed",
    };
  },
  actions: {
    fetchMemberExecutivePositionsForMember() {
      const memberId = useMemberStore().activeMember;
      this.loading = "loading";
      http
        .get(`/admin/member/${memberId}/positions`)
        .then((result) => {
          this.memberExecutivePositions = result.data;
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchMemberExecutivePositionById(id: number) {
      const memberId = useMemberStore().activeMember;
      return http.get(`/admin/member/${memberId}/position/${id}`);
    },
    async createMemberExecutivePosition(
      memberExecutivePosition: CreateMemberExecutivePositionViewModel
    ): Promise<AxiosResponse<any, any>> {
      const memberId = useMemberStore().activeMember;
      const result = await http.post(`/admin/member/${memberId}/position`, {
        note: memberExecutivePosition.note,
        start: memberExecutivePosition.start,
        end: memberExecutivePosition.end,
        executivePositionId: memberExecutivePosition.executivePositionId,
      });
      this.fetchMemberExecutivePositionsForMember();
      return result;
    },
    async updateMemberExecutivePosition(
      memberExecutivePosition: UpdateMemberExecutivePositionViewModel
    ): Promise<AxiosResponse<any, any>> {
      const memberId = useMemberStore().activeMember;
      const result = await http.patch(`/admin/member/${memberId}/position/${memberExecutivePosition.id}`, {
        note: memberExecutivePosition.note,
        start: memberExecutivePosition.start,
        end: memberExecutivePosition.end,
        executivePositionId: memberExecutivePosition.executivePositionId,
      });
      this.fetchMemberExecutivePositionsForMember();
      return result;
    },
    async deleteMemberExecutivePosition(memberExecutivePosition: number): Promise<AxiosResponse<any, any>> {
      const memberId = useMemberStore().activeMember;
      const result = await http.delete(`/admin/member/${memberId}/position/${memberExecutivePosition}`);
      this.fetchMemberExecutivePositionsForMember();
      return result;
    },
  },
});
