import { defineStore } from 'pinia';
import { USER_INFO_STORAGE_KEY } from '../constants';
import { useSessionStorage } from './use-webstorage';

interface IUserInfo {
  id: number;
  username: string;
  is_admin: boolean;
}

function getStorageUserInfo(): IUserInfo {
  let result: IUserInfo = {
    id: -1,
    username: '',
    is_admin: false,
  };

  const value = useSessionStorage().getItem(USER_INFO_STORAGE_KEY) as string;
  if (value) {
    result = JSON.parse(value);
  }

  return result;
}

const useUserInfoStore = defineStore(USER_INFO_STORAGE_KEY, {
  state: () => {
    return getStorageUserInfo();
  },
  actions: {
    setUserInfo: function (val: IUserInfo) {
      this.$state = val;
      useSessionStorage().setItem(USER_INFO_STORAGE_KEY, JSON.stringify(val));
    },
  },
});

export { useUserInfoStore };
