import { defineStore } from 'pinia'
import axios from 'axios'
import { useAuthStore } from './auth'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null,
    loading: false,
    error: null
  }),

  getters: {
    currentUser: (state) => state.user
  },

  actions: {
    async fetchUserProfile() {
      const authStore = useAuthStore()
      const token = authStore.getToken()

      if (!token) {
        this.error = 'No authentication token found'
        throw new Error('No authentication token found')
      }

      this.loading = true
      this.error = null

      try {
        const response = await axios.get('/api/users/me', {
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: 'application/json'
          }
        })

        this.user = response.data
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || 'Failed to fetch user profile'

        if (error.response?.status === 401) {
          authStore.logout()
        }

        throw error
      } finally {
        this.loading = false
      }
    },

    clearUser() {
      this.user = null
      this.error = null
      this.loading = false
    }
  }
})
