import { apiClient } from './apiClient';

export const authService = {
  // Login posts email/password; PHP backend sets session cookie or token
  login: async (email, password) => {
    return apiClient('/auth/login.php', {
      method: 'POST',
      body: { email, password },
    });
  },

  // Check current session user
  getCurrentUser: async () => {
    try {
      const res = await apiClient('/auth/me.php');
      // Extract the nested 'user' object if present
      return res && res.user ? res.user : null;
    } catch (err) {
      // 401 Unauthorized or network errors cleanly return null
      return null;
    }
  },

  // Logout clears session in DB and cookie + resets UI location
  logout: async () => {
    try {
      await apiClient('/auth/logout.php', { method: 'POST' });
    } catch (err) {
      console.warn('Logout API call failed or timed out, performing forced cleanup:', err);
    } finally {
      // 🔑 Redirect to login page and hard-refresh to clear React in-memory state
      window.location.hash = '#/login';
      window.location.reload();
    }
  },
};