import config from '../config';
import { basicAuthConfig } from '../auth0-config';

// Get API URL from config, falling back to relative paths if not set
const API_URL = config.api?.url || '';

// Default mock user for offline/fallback development
const DEFAULT_USER = {
  sub: 'test-user',
  email: 'test@example.com',
  name: 'Test User',
  'https://container-mom.com/roles': ['admin']
};

export const authService = {
  login: async () => {
    try {
      // For basic auth, immediately prompt for password
      if (basicAuthConfig.enabled) {
        const password = window.prompt('Enter test password (default: container-mom-default):');
        if (password) {
          window.sessionStorage.setItem('test_auth_pwd', password);
          // Redirect to homepage after setting password
          window.location.href = '/';
          return;
        }
      }
      
      window.location.href = `${API_URL}/api/auth/login`;
    } catch (error) {
      console.error('Login error:', error);
      throw error;
    }
  },

  logout: async () => {
    try {
      // For basic auth, clear the stored password
      if (basicAuthConfig.enabled) {
        window.sessionStorage.removeItem('test_auth_pwd');
        window.location.href = '/';
        return;
      }
      
      window.location.href = `${API_URL}/api/auth/logout`;
    } catch (error) {
      console.error('Logout error:', error);
      throw error;
    }
  },

  getUser: async () => {
    try {
      // For basic auth with no stored password, return null
      if (basicAuthConfig.enabled && !window.sessionStorage.getItem('test_auth_pwd')) {
        return null;
      }
      
      // Set up headers for the request
      const headers = {
        'Accept': 'application/json'
      };

      // Add Basic Auth header if enabled
      if (basicAuthConfig.enabled) {
        const credentials = btoa(`${basicAuthConfig.username}:${window.sessionStorage.getItem('test_auth_pwd') || ''}`);
        headers['Authorization'] = `Basic ${credentials}`;
      }

      try {
        const response = await fetch(`${API_URL}/api/auth/user`, {
          credentials: 'include',
          headers
        });

        // Log response details for debugging
        console.debug('Auth response status:', response.status);

        if (response.status === 401 && basicAuthConfig.enabled) {
          // If we get a 401 with basic auth, prompt for password
          const password = window.prompt('Enter test password (default: container-mom-default):');
          if (password) {
            // Store temporarily in session storage (will be cleared on page reload/browser close)
            window.sessionStorage.setItem('test_auth_pwd', password);
            // Retry with the password
            return authService.getUser();
          } else {
            return null;
          }
        }

        if (!response.ok) {
          throw new Error(`Failed to get user: ${response.status}`);
        }

        const text = await response.text();
        
        // If the response is empty or whitespace, return null
        if (!text || !text.trim()) {
          console.log('Empty response from server, falling back to default user');
          return basicAuthConfig.enabled && window.sessionStorage.getItem('test_auth_pwd') 
            ? DEFAULT_USER 
            : null;
        }
        
        console.debug('Auth response text:', text);

        try {
          return JSON.parse(text);
        } catch (e) {
          console.error('JSON parse error:', e);
          // Return default user when basic auth is enabled as a fallback
          if (basicAuthConfig.enabled && window.sessionStorage.getItem('test_auth_pwd')) {
            console.log('Using default user due to JSON parse error');
            return DEFAULT_USER;
          }
          return null;
        }
      } catch (networkError) {
        console.error('Network error:', networkError);
        // For basic auth, provide a fallback user when backend is unavailable
        if (basicAuthConfig.enabled && window.sessionStorage.getItem('test_auth_pwd')) {
          console.log('Network error occurred, using default user');
          return DEFAULT_USER;
        }
        return null;
      }
    } catch (error) {
      console.error('Get user error:', error);
      // Default fallback for any errors
      if (basicAuthConfig.enabled && window.sessionStorage.getItem('test_auth_pwd')) {
        return DEFAULT_USER;
      }
      return null;
    }
  }
};

export const isAuthEnabled = () => {
  return basicAuthConfig.enabled;
};
