import axios from 'axios';
import {orisMenu} from './menuList'

const initState = {
  currentUser: null,
  errorMsg: null,
  token: null,
  inited: false,
  my_comp: false
};

const state = {
  ...initState
};

const setCurrentUser = (token) => ({
  position: "",
  first_name: "Сергей",
  last_name: "Шлыков",
  token: token || "12345",
})

const getters = {
  errorMsg:       (state) => state.errorMsg,
  token:          (state) => state.token,
  inited:         (state) => state.inited,
  login:          (state) => state.login,
  password:       (state) => state.password,
  my_comp:        (state) => state.my_comp,
  currentUser:   (state) => state.currentUser,
  menuList:       () => {
    const loggerLevel = import.meta.env.VITE_LOGGER_LEVEL
    if (loggerLevel !== '5' ) {
      return orisMenu.filter(item => item.router !== "tests_adapters")
    }
    return orisMenu
  },
};

const mutations = {
  initAuth: (state, token) => {
    state.currentUser = setCurrentUser(token)
    state.token = token;
    state.inited = true
  },
  set_my_comp:  (state) => state.my_comp,
};


const actions = {
  signin: async ({state}, payload) => {
    let answ = await axios.post(`${import.meta.env.VITE_API_ADDR}/api/auth/login`, {
      "password": payload.login,
      "username": payload.password,
    }, { withCredentials: true }).catch((err) => {
      state.errorMsg = "неверный логин/пароль"
      console.error(err);
    })

    const data = answ?.data || null

    if (data?.authority?.id) {
      const pathname = sessionStorage.getItem("pathname") || "/"
      sessionStorage.removeItem("pathname")
      window.location.replace(pathname);
    } else {
      state.errorMsg = "неверный логин/пароль"
    }
  },

  resetStore: ({commit}) => {
    commit('resetStore')
  }
};

export const store = {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
};
