import { defineStore } from 'pinia'
import { getUser, logout } from '@/api/base'
import type { UserType, ProjectType, OrganizationType, RoleType, PermissionType } from '@/types'

interface State {
  user: UserType | null
  project: ProjectType | null
  organization: OrganizationType | null
  roles: RoleType[]
  permissions: PermissionType[]
}

export const useUserStore = defineStore({
  id: 'user',
  state: (): State => ({
    user: null,
    organization: null,
    project: null,
    roles: [],
    permissions: []
  }),
  getters: {
    isLogin: state => !!state.user
  },
  actions: {
    async getUser() {
      const res = await getUser()
      const { info } = res.data
      const { organization, project, roles, permissions } = res.data.permissions
      this.user = info
      this.organization = organization
      this.project = project
      this.roles = roles
      this.permissions = permissions
    },
    async logout() {
      await logout()
      this.user = null
    }
  }
})
