import { defineStore } from 'pinia'
import { authApi } from '../api'

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

  getters: {
    isAuthenticated: (state) => !!state.token,
    username: (state) => state.user?.username || '',
    roles: (state) => state.user?.roles || [],
    hasRole: (state) => (role) => state.user?.roles?.includes(role) || false,
    isAdmin: (state) => state.user?.roles?.includes('admin') || false
  },

  actions: {
    async login(username, password) {
      try {
        const response = await authApi.login(username, password)
        const { access_token, refresh_token, user } = response.data.data

        this.token = access_token
        this.user = user

        localStorage.setItem('token', access_token)
        localStorage.setItem('refreshToken', refresh_token)
        localStorage.setItem('user', JSON.stringify(user))

        return { success: true }
      } catch (error) {
        const message = error.response?.data?.message || 'Login failed'
        return { success: false, message }
      }
    },

    async logout() {
      try {
        await authApi.logout()
      } catch (e) {
        // Ignore logout errors
      }

      this.token = null
      this.user = null

      localStorage.removeItem('token')
      localStorage.removeItem('refreshToken')
      localStorage.removeItem('user')
    },

    async fetchUser() {
      try {
        const response = await authApi.me()
        this.user = response.data.data
        localStorage.setItem('user', JSON.stringify(this.user))
      } catch (error) {
        this.logout()
      }
    }
  }
})
