/**
 * Auth API client module
 * Following the pattern from static/js/watchlist.js (global exports)
 */

// Use the global API_BASE from auth-utils.js, fallback to /api
const AUTH_API_BASE = typeof window.API_BASE !== 'undefined' ? window.API_BASE : '/api';

async function login(username, password) {
  try {
    const response = await fetch(`${AUTH_API_BASE}/auth/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username, password }),
    });

    const text = await response.text();
    const data = window.safeJsonParse(text, {});

    if (!response.ok) {
      const errorMessage = data.detail || 'Erreur de connexion';
      throw new Error(errorMessage);
    }

    return data;
  } catch (error) {
    if (error instanceof TypeError && error.message.includes('fetch')) {
      throw new Error('Erreur de connexion au serveur');
    }
    throw error;
  }
}

async function register(username, password, email = null, full_name = null) {
  try {
    const response = await fetch(`${AUTH_API_BASE}/auth/register`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username, password, email, full_name }),
    });

    const text = await response.text();
    const data = window.safeJsonParse(text, {});

    if (!response.ok) {
      const errorMessage = data.detail || 'Erreur lors de l\'inscription';
      throw new Error(errorMessage);
    }

    return data;
  } catch (error) {
    if (error instanceof TypeError && error.message.includes('fetch')) {
      throw new Error('Erreur de connexion au serveur');
    }
    throw error;
  }
}

async function logout() {
  try {
    const response = await fetch(`${AUTH_API_BASE}/auth/logout`, { method: 'POST' });
    const text = await response.text();
    const data = window.safeJsonParse(text, { status: 'success' });
    return data;
  } catch (error) {
    return { status: 'success', message: 'Logged out locally' };
  }
}

async function getMe(token) {
  try {
    const response = await fetch(`${AUTH_API_BASE}/auth/me`, {
      headers: { 'Authorization': `Bearer ${token}` },
    });

    const text = await response.text();
    const data = window.safeJsonParse(text, {});

    if (!response.ok) {
      const errorMessage = data.detail || 'Erreur de connexion';
      throw new Error(errorMessage);
    }

    return data;
  } catch (error) {
    if (error instanceof TypeError && error.message.includes('fetch')) {
      throw new Error('Erreur de connexion au serveur');
    }
    throw error;
  }
}

window.authApi = {
  login,
  register,
  logout,
  getMe,
};
