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

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

import { Comment, Ticket } from "../../../../types";
import { ApiException } from "../../../../../../../../ChillMainBundle/Resources/public/types";

export interface State {
  comments: Comment[];
  removedCommentIds: Comment["id"][];
}

export const moduleComment: Module<State, RootState> = {
  state: () => ({
    comments: [] as Comment[],
    removedCommentIds: [] as Comment["id"][],
  }),
  getters: {
    canBeEdited:
      (state: State, getters: unknown, rootState: RootState) =>
      (comment: Comment) => {
        return (
          comment.createdBy?.username === rootState.user.currentUser?.username
        );
      },
    getRemovedCommentIds(state) {
      return state.removedCommentIds;
    },
  },
  mutations: {
    addRemovedCommentIds(state, commentId: number) {
      state.removedCommentIds.push(commentId);
    },
  },
  actions: {
    async createComment({ commit, rootState }, content: Comment["content"]) {
      try {
        const result: Ticket = await makeFetch(
          "POST",
          `/api/1.0/ticket/${rootState.ticket.ticket.id}/comment/add`,
          { content },
        );
        commit("setTicket", result);
      } catch (e: unknown) {
        const error = e as ApiException;
        throw error.name;
      }
    },
    async editComment(
      { commit },
      { id, content }: { id: Comment["id"]; content: Comment["content"] },
    ) {
      try {
        const result: Comment = await makeFetch(
          "POST",
          `/api/1.0/ticket/comment/${id}/edit`,
          { content },
        );
        commit("setTicketHistoryComment", result);
      } catch (e: unknown) {
        const error = e as ApiException;
        throw error.name;
      }
    },
    async deleteComment({ commit }, id: Comment["id"]) {
      try {
        const result: Comment = await makeFetch(
          "POST",
          `/api/1.0/ticket/comment/${id}/delete`,
        );
        commit("setTicketHistoryComment", result);
      } catch (e: unknown) {
        const error = e as ApiException;
        throw error.name;
      }
    },

    async restoreComment({ commit }, id: Comment["id"]) {
      try {
        const result: Comment = await makeFetch(
          "POST",
          `/api/1.0/ticket/comment/${id}/restore`,
        );
        commit("setTicketHistoryComment", result);
      } catch (e: unknown) {
        const error = e as ApiException;
        throw error.name;
      }
    },
  },
};
