import { useAuthStore } from '../stores/auth';
import { createRouter } from 'vue-router';

export function setupAuthInterceptor(app) {
  const authStore = useAuthStore();
  const router = createRouter();

  app.config.globalProperties.$fetch = async (url, options = {}) => {
    try {
      // Add auth header
      const headers = {
        ...options.headers,
        Authorization: `Bearer ${authStore.accessToken}`
      };

      // Make request
      const response = await fetch(url, { ...options, headers });

      if (response.status === 401) {
        if (authStore.refreshToken) {
          try {
            // Try to refresh token
            await authStore.refreshAccessToken();
            
            // Retry original request with new token
            headers.Authorization = `Bearer ${authStore.accessToken}`;
            return await fetch(url, { ...options, headers });
          } catch (error) {
            // Refresh token failed - redirect to login
            authStore.clearTokens();
            router.push('/login');
            throw new Error('Session expired. Please login again.');
          }
        } else {
          // No refresh token - redirect to login
          authStore.clearTokens();
          router.push('/login');
          throw new Error('Authentication required');
        }
      }

      return response;
    } catch (error) {
      console.error('Request failed:', error);
      throw error;
    }
  };
}
