import { defineStore } from 'pinia'
import api from '../axios'
import router from '../router'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: JSON.parse(localStorage.getItem('user')) || null,
    token: localStorage.getItem('token') || null,
    loading: false,
    error: null
  }),

  actions: {
    async initialize() {
      if (this.token) {
        try {
          await this.fetchUser()
        } catch (error) {
          this.clearAuth()
        }
      }
    },

    async register(payload) {
      this.loading = true
      this.error = null

      try {
        const response = await api.post('/register', payload)

        if (response.data.success) {
          this.user = response.data.user
          this.token = response.data.token

          localStorage.setItem('token', this.token)
          localStorage.setItem('user', JSON.stringify(this.user))

          api.defaults.headers.common['Authorization'] = `Bearer ${this.token}`
        }

        return response.data
      } catch (error) {
        this.error =
          error.response?.data?.errors ||
          error.response?.data?.message ||
          'Error en el registro'
        throw error
      } finally {
        this.loading = false
      }
    },

    async login(email, password) {
      this.loading = true
      this.error = null

      try {
        const response = await api.post('/login', { email, password })

        if (response.data.success) {
          this.user = response.data.user
          this.token = response.data.token

          localStorage.setItem('token', this.token)
          localStorage.setItem('user', JSON.stringify(this.user))

          api.defaults.headers.common['Authorization'] = `Bearer ${this.token}`


          await this.fetchUser()

          this.redirectByRole()
        }

        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || 'Error en el login'
        throw error
      } finally {
        this.loading = false
      }
    },

    async fetchUser() {
      try {
        const response = await api.get('/me')

        if (response.data.success) {
          this.user = response.data.user
          localStorage.setItem('user', JSON.stringify(this.user))
        }
      } catch (error) {
        this.clearAuth()
        throw error
      }
    },

    async logout() {
      try {
        if (this.token) {
          await api.post('/logout')
        }
      } catch (error) {
        console.error('Error en logout:', error)
      } finally {
        this.clearAuth()
        router.push('/account/auth/login')
      }
    },

    clearAuth() {
      this.user = null
      this.token = null
      this.error = null

      localStorage.removeItem('token')
      localStorage.removeItem('user')
      delete api.defaults.headers.common['Authorization']
    },

    updateUser(updates) {
      this.user = { ...this.user, ...updates }
      localStorage.setItem('user', JSON.stringify(this.user))
    },

    redirectByRole() {
      if (!this.user || !this.user.roles?.length) {
        router.push('/account/auth/login')
        return
      }

      if (this.user.roles.includes('superadmin')) {
        router.push('/superadmin/dashboard')
      } else if (this.user.roles.includes('administrador')) {
        router.push('/admin/dashboard')
      } else {
        router.push('/usuario/dashboard') 
      }
    }
  },

  getters: {
    isAuth: (state) => !!state.token && !!state.user,

    isSuperAdmin: (state) =>
      state.user?.roles?.includes('superadmin') || false,

    isAdministrador: (state) =>
      state.user?.roles?.includes('administrador') || false,

    isUsuario: (state) =>
      state.user?.roles?.includes('usuario') || false,

    hasRole: (state) => (role) =>
      state.user?.roles?.includes(role) || false,

    hasPermission: (state) => (permission) =>
      state.user?.permissions?.includes(permission) || false,

    isLoading: (state) => state.loading,
    getError: (state) => state.error
  }
})
