import { defineStore } from 'pinia'
import { api, setAuthToken } from '@/api/client'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('vigilcare_token') ?? null,
    user: JSON.parse(localStorage.getItem('vigilcare_user') ?? 'null'),
  }),

  getters: {
    isAuthenticated: (state) => !!state.token,
    role: (state) => state.user?.role ?? null,
    isAdmin: (state) => state.user?.role === 'ADMIN',
    isNurse: (state) => state.user?.role === 'NURSE',
    isPhysician: (state) => state.user?.role === 'PHYSICIAN',
    displayName: (state) =>
      state.user?.displayName ?? state.user?.username ?? 'Unknown user',
    userId: (state) => state.user?.userId ?? null,
  },

  actions: {
    async login(username, password) {
      const data = await api.post('/api/v1/auth/login', { username, password })
      this.token = data.accessToken
      this.user = {
        userId: data.userId,
        username: data.username,
        displayName: data.displayName,
        role: data.role,
      }
      localStorage.setItem('vigilcare_token', this.token)
      localStorage.setItem('vigilcare_user', JSON.stringify(this.user))
      setAuthToken(this.token)
    },

    logout() {
      this.token = null
      this.user = null
      localStorage.removeItem('vigilcare_token')
      localStorage.removeItem('vigilcare_user')
      setAuthToken(null)
    },

    hydrate() {
      if (this.token) setAuthToken(this.token)
    },
  },
})