/* ============================================================
   MyKollectOr® — auth.js — Login / Logout / Rôle v1.1
   ============================================================ */

const Auth = (() => {
  const USER_KEY = 'mko_user';

  const getUser = () => {
    try { return JSON.parse(localStorage.getItem(USER_KEY)); }
    catch { return null; }
  };

  const setUser = (u) => localStorage.setItem(USER_KEY, JSON.stringify(u));

  const isLoggedIn = () => !!Api.getToken();

  const hasRole = (...roles) => {
    const u = getUser();
    return u && roles.includes(u.role);
  };

  const isAdmin      = () => hasRole('admin_fab', 'super_admin');
  const isSuperAdmin = () => hasRole('super_admin');
  const isOperateur  = () => hasRole('operateur_fab');

  const requireRole = (...roles) => {
    if (!isLoggedIn()) { Api.redirectLogin(); return false; }
    if (roles.length && !hasRole(...roles)) {
      Toast.error('Accès refusé — rôle insuffisant');
      setTimeout(() => Api.redirectLogin(), 1200);
      return false;
    }
    return true;
  };

  const requireAdmin    = () => requireRole('admin_fab', 'super_admin');
  const requireOperateur= () => requireRole('operateur_fab', 'admin_fab', 'super_admin');

  // LOGIN — réponse API v1.1 : { error: false, data: { token, refresh_token, user } }
  const login = async (email, password) => {
    // api.js déwrappe automatiquement { error, data } → reçoit directement { token, user, refresh_token }
    const payload = await Api.post('/api/auth/login', { email, password });
    if (!payload || !payload.token) throw new Error('Réponse API invalide');
    Api.setToken(payload.token);
    if (payload.refresh_token) Api.setRefresh(payload.refresh_token);
    setUser(payload.user);
    return payload.user;
  };

  const logout = () => {
    Api.clearAuth();
    const isAdm = window.location.pathname.startsWith('/admin/');
    window.location.href = isAdm ? '/admin/index.html' : '/index.html';
  };

  const populateSidebar = () => {
    const u = getUser();
    if (!u) return;
    const nameEl    = document.getElementById('sidebar-name');
    const roleEl    = document.getElementById('sidebar-role');
    const atelierEl = document.getElementById('sidebar-atelier');
    if (nameEl)    nameEl.textContent    = `${u.prenom || ''} ${u.nom || ''}`.trim() || u.email;
    if (roleEl)    roleEl.textContent    = u.role === 'super_admin' ? 'Super Admin' :
                                           u.role === 'admin_fab'   ? 'Admin MKO'   : 'Opérateur';
    if (atelierEl && u.atelier_nom) atelierEl.textContent = u.atelier_nom;
  };

  const showAdminBadge = () => {
    if (!isAdmin()) return;
    const el = document.getElementById('admin-badge');
    if (el) el.style.display = 'inline-flex';
  };

  return {
    getUser, isLoggedIn, hasRole, isAdmin, isSuperAdmin, isOperateur,
    requireRole, requireAdmin, requireOperateur,
    login, logout, populateSidebar, showAdminBadge
  };
})();
