import { defineStore } from "pinia";
import type {
  CreateMemberViewModel,
  MemberStatisticsViewModel,
  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";

export const useMemberStore = defineStore("member", {
  state: () => {
    return {
      members: [] as Array<MemberViewModel & { tab_pos: number }>,
      totalCount: 0 as number,
      loading: "loading" as "loading" | "fetched" | "failed",
      activeMember: null as number | null,
      activeMemberObj: null as MemberViewModel | null,
      activeMemberStatistics: null as MemberStatisticsViewModel | null,
      loadingActive: "loading" as "loading" | "fetched" | "failed",
    };
  },
  actions: {
    fetchMembers(offset = 0, count = 25, search = "", clear = false) {
      if (clear) this.members = [];
      this.loading = "loading";
      http
        .get(`/admin/member?offset=${offset}&count=${count}${search != "" ? "&search=" + search : ""}`)
        .then((result) => {
          this.totalCount = result.data.total;
          result.data.members
            .filter((elem: MemberViewModel) => this.members.findIndex((m) => m.id == elem.id) == -1)
            .map((elem: MemberViewModel, index: number): MemberViewModel & { tab_pos: number } => {
              return {
                ...elem,
                tab_pos: index + offset,
              };
            })
            .forEach((elem: MemberViewModel & { tab_pos: number }) => {
              this.members.push(elem);
            });
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    async getAllMembers(): Promise<AxiosResponse<any, any>> {
      return await http.get(`/admin/member?noLimit=true`).then((res) => {
        return { ...res, data: res.data.members };
      });
    },
    async getMembersByIds(ids: Array<number>): Promise<AxiosResponse<any, any>> {
      return await http.get(`/admin/member?ids=${ids.join(",")}&noLimit=true`).then((res) => {
        return { ...res, data: res.data.members };
      });
    },
    async searchMembers(search: string): Promise<AxiosResponse<any, any>> {
      return await http.get(`/admin/member?search=${search}&noLimit=true`).then((res) => {
        return { ...res, data: res.data.members };
      });
    },
    fetchMemberByActiveId() {
      this.loadingActive = "loading";
      http
        .get(`/admin/member/${this.activeMember}`)
        .then((res) => {
          this.activeMemberObj = res.data;
          this.loadingActive = "fetched";
        })
        .catch((err) => {
          this.loadingActive = "failed";
        });
    },
    fetchMemberById(id: number) {
      return http.get(`/admin/member/${id}`);
    },
    fetchMemberStatisticsByActiveId() {
      http
        .get(`/admin/member/${this.activeMember}/statistics`)
        .then((res) => {
          this.activeMemberStatistics = res.data;
        })
        .catch((err) => {});
    },
    fetchMemberStatisticsById(id: number) {
      return http.get(`/admin/member/${id}/statistics`);
    },
    async createMember(member: CreateMemberViewModel): Promise<AxiosResponse<any, any>> {
      const result = await http.post(`/admin/member`, {
        salutation: member.salutation,
        firstname: member.firstname,
        lastname: member.lastname,
        nameaffix: member.nameaffix,
        birthdate: member.birthdate,
        internalId: member.internalId,
      });
      this.fetchMembers();
      return result;
    },
    async updateActiveMember(member: UpdateMemberViewModel): Promise<AxiosResponse<any, any>> {
      const result = await http.patch(`/admin/member/${member.id}`, {
        salutation: member.salutation,
        firstname: member.firstname,
        lastname: member.lastname,
        nameaffix: member.nameaffix,
        birthdate: member.birthdate,
        internalId: member.internalId,
      });
      this.fetchMembers();
      return result;
    },
    async deleteMember(member: number): Promise<AxiosResponse<any, any>> {
      const result = await http.delete(`/admin/member/${member}`);
      this.fetchMembers();
      return result;
    },
    async printMemberList() {
      return http.get(`/admin/member/print/namelist`, {
        responseType: "blob",
      });
    },
  },
});
