import { Module } from "vuex";
import { RootState } from "..";
import { TicketFilterParams, TicketSimple } from "../../../../types";
import {
  makeFetch,
  Pagination,
  PaginationResponse,
} from "ChillMainAssets/lib/api/apiMethods";
import {
  ApiException,
  User,
} from "../../../../../../../../ChillMainBundle/Resources/public/types";

export interface State {
  ticket_list: TicketSimple[];
  pagination: Pagination;
  count: number;
  user: User;
}

export const moduleTicketList: Module<State, RootState> = {
  state: () => ({
    ticket_list: [],
    pagination: {
      first: 0,
      items_per_page: 50,
      more: false,
      next: null,
      previous: null,
    },
    count: 0,
    user: {} as User,
  }),
  getters: {
    getTicketList(state): TicketSimple[] {
      return state.ticket_list;
    },
    getPreviousTicketList(state, getters, rootState): TicketSimple[] {
      return state.ticket_list.filter(
        (ticket) => ticket.id !== rootState.ticket.ticket.id,
      );
    },
    getPagination(state) {
      return state.pagination;
    },
    getUser(state): User {
      return state.user;
    },
    getCount(state): number {
      return state.count;
    },
  },
  mutations: {
    setTicketList(state, ticketList: TicketSimple[]) {
      state.ticket_list = ticketList;
    },
    setPagination(state, pagination: State["pagination"]) {
      state.pagination = pagination;
    },
    setUser(state, user: User) {
      state.user = user;
    },
    setCount(state, count: number) {
      state.count = count;
    },
  },
  actions: {
    async fetchTicketList(
      { commit },
      ticketFilterParams: TicketFilterParams | null,
    ) {
      try {
        let params = "";
        if (ticketFilterParams) {
          const filteredParams = Object.fromEntries(
            Object.entries(ticketFilterParams).filter(
              ([, value]) =>
                value !== null &&
                value !== null &&
                (value === true ||
                  (typeof value === "number" && !isNaN(value)) ||
                  (typeof value === "string" && value !== "") ||
                  (Array.isArray(value) && value.length > 0)),
            ),
          );
          params = new URLSearchParams(
            filteredParams as Record<string, string>,
          ).toString();
        }

        const { results, pagination, count } = (await makeFetch(
          "GET",
          `/api/1.0/ticket/ticket/list/?${params}`,
        )) as PaginationResponse<TicketSimple>;

        commit("setTicketList", results);
        commit("setCount", count);
        commit("setPagination", pagination);
      } catch (e: unknown) {
        const error = e as ApiException;
        console.error(
          "Erreur lors du chargement de la liste des tickets:",
          error,
        );
      }
    },
    async fetchConnectedUser({ commit }) {
      try {
        const user = await makeFetch("GET", "/api/1.0/main/whoami.json");
        commit("setUser", user);
        return user;
      } catch (error) {
        console.error(
          "Erreur lors de la récupération de l'utilisateur connecté:",
          error as ApiException,
        );
        throw error;
      }
    },
    async fetchTicketListByUrl({ commit, state }, url: string) {
      try {
        const { results, pagination, count } = (await makeFetch(
          "GET",
          url,
        )) as PaginationResponse<TicketSimple>;
        commit("setTicketList", [...state.ticket_list, ...results]);
        commit("setCount", count);
        commit("setPagination", pagination);
      } catch (e: unknown) {
        const error = e as ApiException;
        console.error(
          "Erreur lors du chargement de la liste des tickets par URL:",
          error,
        );
      }
    },
  },
};
