import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '../axiosPostulante'

export const useAuthStore = defineStore('auth', () => {

  const token = ref(localStorage.getItem('postulante_token') || null)
  const postulante = ref(JSON.parse(localStorage.getItem('postulante_data') || 'null'))
  const loading = ref(false)
  const error = ref(null)

  const isAuthenticated = computed(() => !!token.value)
  const userDni = computed(() => postulante.value?.dni || null)
  const userEmail = computed(() => postulante.value?.email || null)
  const userName = computed(() => postulante.value?.name || null)
  const userId = computed(() => postulante.value?.id || null)


  const register = async ({ name, email, password, password_confirmation, dni }) => {
    try {
      loading.value = true
      error.value = null

      const response = await api.post('/postulante/register', {
        name,
        email,
        password,
        password_confirmation,
        dni
      })

      if (response.data.success) {
        token.value = response.data.token
        postulante.value = response.data.postulante

        localStorage.setItem('postulante_token', token.value)
        localStorage.setItem('postulante_data', JSON.stringify(postulante.value))

        return { success: true }
      }

      return { success: false, error: response.data.message || 'Error en registro' }
    } catch (err) {
      error.value = err.response?.data?.message || 'Error en registro'
      return { success: false, error: error.value }
    } finally {
      loading.value = false
    }
  }

  const login = async ({ email, password, device_id = null }) => {
    try {
      loading.value = true
      error.value = null

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

      if (response.data.success) {
        token.value = response.data.token
        postulante.value = response.data.postulante

        localStorage.setItem('postulante_token', token.value)
        localStorage.setItem('postulante_data', JSON.stringify(postulante.value))

        return { success: true }
      }

      return { success: false, error: response.data.message || 'Credenciales inválidas' }
    } catch (err) {
      error.value = err.response?.data?.message || 'Error en login'
      return { success: false, error: error.value }
    } finally {
      loading.value = false
    }
  }


  const logout = async () => {
    try {
      if (token.value) {
        await api.post('/postulante/logout', {}, {
          headers: { Authorization: `Bearer ${token.value}` }
        })
      }
    } catch (err) {
      console.error('Error en logout:', err)
    } finally {
      token.value = null
      postulante.value = null
      localStorage.removeItem('postulante_token')
      localStorage.removeItem('postulante_data')
    }
  }

  const checkAuth = async () => {
    if (!token.value) return false

    try {
      const response = await api.get('/postulante/me', {
        headers: { Authorization: `Bearer ${token.value}` }
      })

      if (response.data.success) {
        postulante.value = response.data.postulante
        return true
      }
    } catch (err) {
      console.error('Error verificando autenticación:', err)
      await logout()
    }

    return false
  }

  return {

    token,
    postulante,
    loading,
    error,

    isAuthenticated,
    userDni,
    userEmail,
    userName,
    userId,

    register,
    login,
    logout,
    checkAuth
  }
})
