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 {
  CreateMembershipViewModel,
  MembershipViewModel,
  UpdateMembershipViewModel,
} from "@/viewmodels/admin/membership.models";

export const useMembershipStore = defineStore("membership", {
  state: () => {
    return {
      memberships: [] as Array<MembershipViewModel>,
      loading: "loading" as "loading" | "fetched" | "failed",
    };
  },
  actions: {
    fetchMembershipsForMember() {
      const memberId = useMemberStore().activeMember;
      this.loading = "loading";
      http
        .get(`/admin/member/${memberId}/memberships`)
        .then((result) => {
          this.memberships = result.data;
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchMembershipById(id: number) {
      const memberId = useMemberStore().activeMember;
      return http.get(`/admin/member/${memberId}/membership/${id}`);
    },
    async createMembership(membership: CreateMembershipViewModel): Promise<AxiosResponse<any, any>> {
      const memberId = useMemberStore().activeMember;
      const result = await http.post(`/admin/member/${memberId}/membership`, {
        start: membership.start,
        statusId: membership.statusId,
      });
      this.fetchMembershipsForMember();
      return result;
    },
    async updateMembership(membership: UpdateMembershipViewModel): Promise<AxiosResponse<any, any>> {
      const memberId = useMemberStore().activeMember;
      const result = await http.patch(`/admin/member/${memberId}/membership/${membership.id}`, {
        start: membership.start,
        end: membership.end,
        terminationReason: membership.terminationReason,
        statusId: membership.statusId,
      });
      this.fetchMembershipsForMember();
      return result;
    },
    async deleteMembership(membership: number): Promise<AxiosResponse<any, any>> {
      const memberId = useMemberStore().activeMember;
      const result = await http.delete(`/admin/member/${memberId}/membership/${membership}`);
      this.fetchMembershipsForMember();
      return result;
    },
  },
});
