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 {
  CreateMemberAwardViewModel,
  MemberAwardViewModel,
  UpdateMemberAwardViewModel,
} from "@/viewmodels/admin/memberAward.models";

export const useMemberAwardStore = defineStore("memberAward", {
  state: () => {
    return {
      memberAwards: [] as Array<MemberAwardViewModel>,
      loading: "loading" as "loading" | "fetched" | "failed",
    };
  },
  actions: {
    fetchMemberAwardsForMember() {
      const memberId = useMemberStore().activeMember;
      this.loading = "loading";
      http
        .get(`/admin/member/${memberId}/awards`)
        .then((result) => {
          this.memberAwards = result.data;
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchMemberAwardById(id: number) {
      const memberId = useMemberStore().activeMember;
      return http.get(`/admin/member/${memberId}/award/${id}`);
    },
    async createMemberAward(memberAward: CreateMemberAwardViewModel): Promise<AxiosResponse<any, any>> {
      const memberId = useMemberStore().activeMember;
      const result = await http.post(`/admin/member/${memberId}/award`, {
        given: memberAward.given,
        note: memberAward.note,
        date: memberAward.date,
        awardId: memberAward.awardId,
      });
      this.fetchMemberAwardsForMember();
      return result;
    },
    async updateMemberAward(memberAward: UpdateMemberAwardViewModel): Promise<AxiosResponse<any, any>> {
      const memberId = useMemberStore().activeMember;
      const result = await http.patch(`/admin/member/${memberId}/award/${memberAward.id}`, {
        given: memberAward.given,
        note: memberAward.note,
        date: memberAward.date,
        awardId: memberAward.awardId,
      });
      this.fetchMemberAwardsForMember();
      return result;
    },
    async deleteMemberAward(memberAward: number): Promise<AxiosResponse<any, any>> {
      const memberId = useMemberStore().activeMember;
      const result = await http.delete(`/admin/member/${memberId}/award/${memberAward}`);
      this.fetchMemberAwardsForMember();
      return result;
    },
  },
});
