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

const API_URL = config.api.url || '';

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}/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}/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) {
        // We only encode the username here since the password will be validated on the server
        // The actual password is never stored in the frontend for security reasons
        const credentials = btoa(`${basicAuthConfig.username}:${window.sessionStorage.getItem('test_auth_pwd') || ''}`);
        headers['Authorization'] = `Basic ${credentials}`;
      }

      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(); // Fixed to use authService instead of this
        } else {
          return null;
        }
      }

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

      const text = await response.text();
      console.debug('Auth response text:', text);

      try {
        return text ? JSON.parse(text) : null;
      } catch (e) {
        console.error('JSON parse error:', e);
        return null;
      }
    } catch (error) {
      console.error('Get user error:', error);
      return null;
    }
  }
};

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