// [DEF:authStore:Store]
// @TIER: STANDARD
// @SEMANTICS: auth, store, svelte, jwt, session
// @PURPOSE:   Manages the global authentication state on the frontend.
// @LAYER:     Feature
// @RELATION:  MODIFIED_BY -> handleLogin, handleLogout
// @RELATION:  BINDS_TO -> Navbar, ProtectedRoute

import { writable } from 'svelte/store';
import { browser } from '$app/environment';

// [DEF:AuthState:Interface]
/**
 * @purpose Defines the structure of the authentication state.
 */
export interface AuthState {
    user: any | null;
    token: string | null;
    isAuthenticated: boolean;
    loading: boolean;
}
// [/DEF:AuthState:Interface]

const initialState: AuthState = {
    user: null,
    token: browser ? localStorage.getItem('auth_token') : null,
    isAuthenticated: false,
    loading: true
};

// [DEF:createAuthStore:Function]
/**
 * @purpose Creates and configures the auth store with helper methods.
 * @pre No preconditions - initialization function.
 * @post Returns configured auth store with subscribe, setToken, setUser, logout, setLoading methods.
 * @returns {Writable<AuthState>}
 */
function createAuthStore() {
    const { subscribe, set, update } = writable<AuthState>(initialState);

    return {
        subscribe,
        // [DEF:setToken:Function]
        /**
         * @purpose Updates the store with a new JWT token.
         * @pre token must be a valid JWT string.
         * @post Store updated with new token, isAuthenticated set to true.
         * @param {string} token - The JWT access token.
         */
        setToken: (token: string) => {
            console.log("[setToken][Action] Updating token");
            if (browser) {
                localStorage.setItem('auth_token', token);
            }
            update(state => ({ ...state, token, isAuthenticated: !!token }));
        },
        // [/DEF:setToken:Function]
        // [DEF:setUser:Function]
        /**
         * @purpose Sets the current user profile data.
         * @pre User object must contain valid profile data.
         * @post Store updated with user, isAuthenticated true, loading false.
         * @param {any} user - The user profile object.
         */
        setUser: (user: any) => {
            console.log("[setUser][Action] Setting user profile");
            update(state => ({ ...state, user, isAuthenticated: !!user, loading: false }));
        },
        // [/DEF:setUser:Function]
        // [DEF:logout:Function]
        /**
         * @purpose Clears authentication state and storage.
         * @pre User is currently authenticated.
         * @post Auth token removed from localStorage, store reset to initial state.
         */
        logout: () => {
            console.log("[logout][Action] Logging out");
            if (browser) {
                localStorage.removeItem('auth_token');
            }
            set({ user: null, token: null, isAuthenticated: false, loading: false });
        },
        // [/DEF:logout:Function]
        // [DEF:setLoading:Function]
        /**
         * @purpose Updates the loading state.
         * @pre None.
         * @post Store loading state updated.
         * @param {boolean} loading - Loading status.
         */
        setLoading: (loading: boolean) => {
            console.log(`[setLoading][Action] Setting loading to ${loading}`);
            update(state => ({ ...state, loading }));
        }
        // [/DEF:setLoading:Function]
    };
}
// [/DEF:createAuthStore:Function]

export const auth = createAuthStore();

// [/DEF:authStore:Store]