import { cloneDeep } from 'lodash';
import { api } from 'src/boot/axios';
import { ActionTree } from 'vuex';
import { run } from '../helpers';
import { ClientesState } from './ClientesState';

export const actions: ActionTree<ClientesState, unknown> = {
  create: async ({ state }, payload) => {
    state.loading = true;
    return run(api.post('clientes', payload), 'Cliente agregado correctamente', 'Error al guardar el CLIENTE').finally(() => (state.loading = false));
  },
  update: async ({ state, commit }, payload) => {
    state.loading = true;
    return run(api.put('clientes/' + payload.ID_CLIENTE, payload), 'CLIENTE guardado correctamente', 'Error al guardar el CLIENTE')
      .then((data) => {
        if (data.ID_CLIENTE === state.current?.ID_CLIENTE) {
          commit('setCurrent', { ...cloneDeep(state.current), ...data });
        }
        return data;
      })
      .finally(() => (state.loading = false));
  },
  getOne: async ({ state, commit }, id) => {
    state.loading = true;
    run(api.get(`clientes/${id}`))
      .then((data) => commit('setCurrent', data))
      .finally(() => (state.loading = false));
  },
  saveLocation: async ({ state }, { id, data }) => {
    state.loading = true;
    return run(api.put(`clientes/${id}/location`, data), 'Ubicación guardada correctamente', 'Error al guardar la ubicación').finally(() => (state.loading = false));
  },
};
