import api from './api';

export const login = async (username, password) => {
  try {
    const response = await api.post('/auth/login', {
      username: username.trim(),
      password
    });
    if (response.data.success) {
      sessionStorage.setItem('user', JSON.stringify(response.data.user));
      return { success: true, user: response.data.user };
    }
    return { success: false, message: response.data.message || 'Anmeldung fehlgeschlagen' };
  } catch (error) {
    // Validation errors (400) – show field-level messages
    if (error.response?.data?.errors?.length) {
      const msg = error.response.data.errors.map(e => e.msg).join(' · ');
      return { success: false, message: msg };
    }
    // Auth errors (401) or other server errors with a message
    if (error.response?.data?.message) {
      return { success: false, message: error.response.data.message };
    }
    // Network or unknown errors
    if (error.code === 'ERR_NETWORK' || error.code === 'ECONNABORTED') {
      return { success: false, message: 'Server nicht erreichbar. Bitte Verbindung prüfen.' };
    }
    return { success: false, message: 'Anmeldung fehlgeschlagen. Bitte erneut versuchen.' };
  }
};

export const logout = async () => {
  try {
    // Call backend to clear httpOnly cookie
    await api.post('/auth/logout');
    // Clear user data from sessionStorage
    sessionStorage.removeItem('user');
  } catch (error) {
    // Even if logout API fails, clear local user data
    sessionStorage.removeItem('user');
  }
};

export const getStoredUser = () => {
  const userStr = sessionStorage.getItem('user');
  return userStr ? JSON.parse(userStr) : null;
};

export const isAuthenticated = () => {
  // We can't check httpOnly cookie from JavaScript
  // Check if user data exists (set during login)
  return !!sessionStorage.getItem('user');
};
