import { defineStore } from 'pinia';
import axios from 'axios';
import { ref, computed } from 'vue';

export const useAuthStore = defineStore('auth', () => {
  // State
  const token = ref(localStorage.getItem('token') || null);
  const user = ref(null);
  const loading = ref(false);
  const error = ref(null);
  
  // Getters
  const isAuthenticated = computed(() => !!token.value);
  const getUser = computed(() => user.value);
  const getToken = computed(() => token.value);
  const isLoading = computed(() => loading.value);
  const getError = computed(() => error.value);
  
  // Actions
  function setToken(newToken) {
    token.value = newToken;
    localStorage.setItem('token', newToken);
  }
  
  function setUser(newUser) {
    user.value = newUser;
  }
  
  function logout() {
    token.value = null;
    user.value = null;
    localStorage.removeItem('token');
  }
  
  async function login(email, password) {
    loading.value = true;
    error.value = null;
    
    try {
      const response = await axios.post('/api/login', { email, password });
      
      setToken(response.data.token);
      setUser(response.data.user);
      
      // Set the Authorization header for all future requests
      axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`;
      
      return response;
    } catch (error) {
      error.value = error.response?.data?.message || 'An error occurred during login';
      throw error;
    } finally {
      loading.value = false;
    }
  }
  
  async function register(name, email, password, passwordConfirmation) {
    loading.value = true;
    error.value = null;
    
    try {
      const response = await axios.post('/api/register', {
        name,
        email,
        password,
        password_confirmation: passwordConfirmation
      });
      
      setToken(response.data.token);
      setUser(response.data.user);
      
      // Set the Authorization header for all future requests
      axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`;
      
      return response;
    } catch (error) {
      error.value = error.response?.data?.message || 'An error occurred during registration';
      throw error;
    } finally {
      loading.value = false;
    }
  }
  
  async function fetchUser() {
    if (!token.value) return;
    
    loading.value = true;
    error.value = null;
    
    try {
      const response = await axios.get('/api/user');
      setUser(response.data);
      return response;
    } catch (error) {
      error.value = error.response?.data?.message || 'An error occurred while fetching user data';
      
      // If the token is invalid, clear the auth state
      if (error.response?.status === 401) {
        token.value = null;
        user.value = null;
        localStorage.removeItem('token');
        delete axios.defaults.headers.common['Authorization'];
      }
      
      throw error;
    } finally {
      loading.value = false;
    }
  }
  
  function initAuth() {
    if (token.value) {
      axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`;
      fetchUser();
    }
  }
  
  return {
    // State
    token,
    user,
    loading,
    error,
    
    // Getters
    isAuthenticated,
    getUser,
    getToken,
    isLoading,
    getError,
    
    // Actions
    setToken,
    setUser,
    logout,
    login,
    register,
    fetchUser,
    initAuth
  };
}); 