import { writable } from 'svelte/store';
import { browser } from '$app/environment';
import { get } from '$lib/api/client.js';

/**
 * Create auth store with cookie-based authentication
 */
function createAuthStore() {
  const { subscribe, set, update } = writable({
    user: null,
    isAuthenticated: false,
    loading: true,
  });

  return {
    subscribe,

    /**
     * Set user data after successful login
     * Token is stored in HTTP-only cookie by backend
     * @param {Object} user - User object
     */
    login: (user) => {
      set({ user, isAuthenticated: true, loading: false });
    },

    /**
     * Clear authentication data on logout
     */
    logout: () => {
      set({ user: null, isAuthenticated: false, loading: false });
    },

    /**
     * Update user data without changing auth status
     * @param {Object} user - Updated user object
     */
    setUser: (user) => {
      update((state) => ({ ...state, user }));
    },

    /**
     * Check if user is authenticated via cookie
     * @returns {Promise<boolean>}
     */
    checkAuth: async () => {
      if (!browser) return false;
      
      try {
        const response = await get('/api/auth/check');
        
        // Backend returns user data nested under response.data
        const userData = response.data || response;
        if (response.status === 'success' && userData.userid) {
          const user = {
            id: userData.userid,
            username: userData.username,
            name: userData.NameFirst && userData.NameLast 
              ? `${userData.NameFirst} ${userData.NameLast}` 
              : userData.username,
            ...userData
          };
          set({ user, isAuthenticated: true, loading: false });
          return true;
        } else {
          set({ user: null, isAuthenticated: false, loading: false });
          return false;
        }
      } catch (error) {
        console.error('Auth check failed:', error.message);
        set({ user: null, isAuthenticated: false, loading: false });
        return false;
      }
    },

    /**
     * Set loading state
     * @param {boolean} loading
     */
    setLoading: (loading) => {
      update((state) => ({ ...state, loading }));
    },
  };
}

export const auth = createAuthStore();
