import { defineStore } from 'pinia';
import axios from 'boot/axios';

export const useAuthStore = defineStore('auth', {
  state: () => ({
    isAuthenticated: false,
    user: null,
    loading: false, // Optional: track loading state
    error: null, // Optional: track errors
  }),
  actions: {
    async checkAuthStatus() 
    {
      this.loading = true;
      this.error = null;
      try 
      {
        const res = await axios.get('/api/auth/status', {
          withCredentials: true, // Ensure cookies are sent with the request
        });
        if (res.data.status === 'authenticated') 
        {
          this.isAuthenticated = true;
          this.user = res.data.user;
        }
        else 
        {
          this.isAuthenticated = false;
          this.user = null;
        }
      }
      catch (error) 
      {
        // console.error('Failed to check authentication status:', error);
        this.error = 'Could not verify login status.';
        this.isAuthenticated = false;
        this.user = null;
      }
      finally 
      {
        this.loading = false;
      }
    },
    // Action to manually set user as logged out (e.g., after logout)
    logout() 
    {
      this.isAuthenticated = false;
      this.user = null;
    }
  },
});
