import axios from "axios";

const state = {
    lastFetch: null,
    grupo_de_compra_id: null,
    nombre: null,
    devoluciones_habilitadas: null,
    pedidos: null,
    total_a_recaudar: null,
    total_barrial: null,
    total_devoluciones: null,
    total_a_transferir: null,
    total_transporte: null,
    cantidad_transporte: null,
};

const mutations = {
    setState(state, { grupo_de_compra }) {
        state.lastFetch = new Date();
        state.grupo_de_compra_id = grupo_de_compra.id;
        state.nombre = grupo_de_compra.nombre;
        state.devoluciones_habilitadas = grupo_de_compra.devoluciones_habilitadas;
        state.pedidos = grupo_de_compra.pedidos;
        state.total_a_recaudar = grupo_de_compra.total_a_recaudar;
        state.total_barrial = grupo_de_compra.total_barrial;
        state.total_devoluciones = grupo_de_compra.total_devoluciones;
        state.total_a_transferir = grupo_de_compra.total_a_transferir;
        state.total_transporte = grupo_de_compra.total_transporte;
        state.cantidad_transporte = grupo_de_compra.cantidad_transporte;
    },
    toggleCaracteristica(state, { caracteristica_id }) {
        state[`${caracteristica_id}_habilitadas`] = !state[`${caracteristica_id}_habilitadas`];
    }
};

const actions = {
    async getGrupoDeCompra({ commit }) {
        const response = await axios.get('/user/grupo_de_compra');
        commit('setState', response.data);
    },
    async setAprobacionPedido({ commit }, { pedido_id, aprobacion }){
        await axios.post("/api/admin/subpedidos/" + pedido_id + "/aprobacion", { aprobacion: aprobacion });
        await actions.getGrupoDeCompra({ commit });
    },
    async toggleCaracteristica({ commit }, { caracteristica_id }) {
        await axios.post(`/api/grupos-de-compra/${state.grupo_de_compra_id}/${caracteristica_id}`);
        commit('toggleCaracteristica', { caracteristica_id: caracteristica_id })
    },
};

const getters = {
    grupoDeCompraDefinido() {
      return state.lastFetch !== null;
    },
    hayPedidos() {
        return getters.grupoDeCompraDefinido() && state.pedidos.length > 0;
    },
    pedidosAprobados() {
        return getters.grupoDeCompraDefinido() ? state.pedidos.filter(p => p.aprobado) : [];
    },
    hayAprobados() {
        return getters.pedidosAprobados().length !== 0;
    },
    getPedido() {
        return (pedido_id) => state.pedidos.find(p => p.id === pedido_id);
    },
    getCaracteristica() {
        return (caracteristica) => state[`${caracteristica}_habilitadas`];
    }
};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters,
};