import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useAuthStore = defineStore('auth', () => {
  const token = ref<string | null>(null)
  const perfil = ref<any>(null)
  const getToken = computed(() => token.value)
  const getPerfil = computed(() => perfil.value)
  const isAuthenticated = computed(() => !!getToken.value)

  const setToken = async (data: { token?: string; user?: any} | null) => {
    token.value = data?.token || null
    if (token.value) {
      await setPerfil(data)
    } else {
      perfil.value = null
    }
  }

  const setPerfil = async (data: any | null) => {
    perfil.value = data?.user || null
  }

  const clearAuth = () => {
    token.value = null
    perfil.value = null
  }

  return { 
    setToken,
    setPerfil,
    clearAuth,
    isAuthenticated,
    getToken,
    getPerfil,
    token,
    perfil
  }
}, {
  persist: {
    storage: persistedState.cookiesWithOptions({
      maxAge: 60 * 60 * 24 * 7
    })
  }
})