// src/stores/auth.ts

import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import axios from 'axios'
import { authService } from '../services/authService'

interface User {
  user_name: string;
  user_id: number;
}

export const useAuthStore = defineStore('auth', () => {
  // --- STATE ---
  const token = ref(localStorage.getItem('auth_token') || null)
  const user = ref<User | null>(null)
  const storedUser = localStorage.getItem('auth_user')
  if (storedUser) {
    try {
      user.value = JSON.parse(storedUser)
    } catch {
      // Invalid JSON, clear it
      localStorage.removeItem('auth_user')
    }
  }

  // --- GETTERS ---
  const isAuthenticated = computed(() => !!token.value)

  // --- ACTIONS ---
  function setToken(newToken: string, newUser?: User) {
    // For debugging: confirms this function is being called correctly from Login.vue
    console.log('Pinia Action [setToken] called with:', { newToken, newUser });

    localStorage.setItem('auth_token', newToken)
    token.value = newToken
    if (newUser) {
      localStorage.setItem('auth_user', JSON.stringify(newUser))
      user.value = newUser
    }

    // --- THIS IS THE FIX ---
    // The string must be a template literal (using backticks ``)
    // and should follow the "Bearer <token>" format.
    axios.defaults.headers.common['Authorization'] = `Bearer ${newToken}`

    console.log('Token and user have been set in localStorage and Axios headers.');
  }

  function clearAuth() {
    localStorage.removeItem('auth_token')
    localStorage.removeItem('auth_user')
    token.value = null
    user.value = null
    delete axios.defaults.headers.common['Authorization']
  }

  async function checkAuthStatus() {
    if (!isAuthenticated.value) {
      return false // No token, definitely not authenticated
    }
    try {
      // Use the centralized auth service
      const response = await authService.whoami();
      if (response.data && response.data.ok) {
        user.value = response.data.user
        return true
      }
      // If the token is invalid, the API returns an error, which will be caught
      clearAuth()
      return false
    } catch {
      clearAuth()
      return false
    }
  }

  // --- RETURN ---
  return {
    token,
    user,
    isAuthenticated,
    setToken,
    clearAuth,
    checkAuthStatus,
  }
})
