/*
 * Copyright (c) 2023-2024 Rackslab
 *
 * This file is part of Slurm-web.
 *
 * SPDX-License-Identifier: MIT
 */

import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Ref } from 'vue'
import type { RouteLocationRaw } from 'vue-router'

export const useAuthStore = defineStore('auth', () => {
  const token: Ref<string | null> = ref(localStorage.getItem('token'))
  const username: Ref<string | null> = ref(localStorage.getItem('username'))
  const fullname: Ref<string | null> = ref(localStorage.getItem('fullname'))
  const groups: Ref<Array<string> | null> = ref(
    JSON.parse(localStorage.getItem('groups') || '[]') as string[]
  )
  const returnUrl: Ref<string | null> = ref(null)

  function setSession(_token: string, _username: string, _fullname: string, _groups: string[]) {
    token.value = _token
    username.value = _username
    fullname.value = _fullname
    groups.value = _groups

    localStorage.setItem('token', _token)
    localStorage.setItem('username', _username)
    localStorage.setItem('fullname', _fullname)
    localStorage.setItem('groups', JSON.stringify(_groups))
  }

  function takePostLoginRoute(): string | RouteLocationRaw {
    const redirectUrl = returnUrl.value || { name: 'clusters' }
    returnUrl.value = null
    return redirectUrl
  }

  function logout() {
    token.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('username')
    localStorage.removeItem('fullname')
    localStorage.removeItem('groups')
  }

  return { token, username, fullname, groups, returnUrl, setSession, takePostLoginRoute, logout }
})
