import {get, post} from '../apiHelpers'
import {groupBy} from 'ramda'
import {toRaw} from "vue"
import {cond, T, equals} from 'ramda'
import axios from 'axios';
import {orisMenu} from './menuList'

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

const state = {
  ...initState
};

const current_user = (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,
  current_user:   (state) => state.current_user,
  menuList:       () => orisMenu,
};

const mutations = {
  initAuth: (state, token) => {
    state.current_user = current_user(token)
    state.token = token;
    state.inited = true
  },
  set_my_comp:  (state, upd) => 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,
};
