import {
  fetchResults,
  makeFetch,
} from "../../../../../../../../ChillMainBundle/Resources/public/lib/api/apiMethods";

import type { RootState } from "..";
import type { Module } from "vuex";

import {
  ApiException,
  User,
  UserGroup,
  UserGroupOrUser,
} from "../../../../../../../../ChillMainBundle/Resources/public/types";

export interface State {
  userGroups: UserGroup[];
  users: User[];
}

export const moduleAddressee: Module<State, RootState> = {
  state: () => ({
    userGroups: [] as UserGroup[],
    users: [] as User[],
  }),
  getters: {
    getUserGroups(state) {
      return state.userGroups;
    },
    getUsers(state) {
      return state.users;
    },
  },
  mutations: {
    setUserGroups(state, userGroups) {
      state.userGroups = userGroups;
    },
    setUsers(state, users) {
      state.users = users;
    },
  },
  actions: {
    fetchUserGroups({ commit }) {
      try {
        fetchResults("/api/1.0/main/user-group.json").then((results) => {
          commit("setUserGroups", results);
        });
      } catch (e: unknown) {
        const error = e as ApiException;
        throw error.name;
      }
    },
    fetchUsers({ commit }) {
      try {
        fetchResults("/api/1.0/main/user.json").then((results) => {
          commit("setUsers", results);
        });
      } catch (e: unknown) {
        const error = e as ApiException;
        throw error.name;
      }
    },

    async setAddressees({ commit, rootState }, addressees: UserGroupOrUser[]) {
      try {
        const result = await makeFetch(
          "POST",
          `/api/1.0/ticket/${rootState.ticket.ticket.id}/addressees/set`,
          {
            addressees: addressees.map((addressee) => {
              return { id: addressee.id, type: addressee.type };
            }),
          },
        );
        commit("setTicket", result);
      } catch (e: unknown) {
        const error = e as ApiException;
        throw error.name;
      }
    },
  },
};
