// ================= Auth service seam =================
function getCurrentRole() {
  return state.currentRole || loadFromStorage(STORAGE_KEYS.currentRole, ROLES.PATIENT);
}

function setCurrentRoleForPrototype(role) {
  if (!Object.values(ROLES).includes(role)) return false;
  state.currentRole = role;
  saveToStorage(STORAGE_KEYS.currentRole, role);
  return true;
}

function isAdminRole(role = getCurrentRole()) {
  return role === ROLES.ADMIN;
}

function isPatientRole(role = getCurrentRole()) {
  return role === ROLES.PATIENT;
}

function isAuthRequired() {
  return Boolean(APP_CONFIG.authRequired || APP_CONFIG.dataMode === DATA_MODES.FIREBASE);
}

function prototypeUserForRole(role = getCurrentRole()) {
  return {
    uid: role === ROLES.ADMIN ? "prototype-admin" : patient.id,
    email: role === ROLES.ADMIN ? "admin@leaner.local" : "sarah@leaner.local",
    firstName: role === ROLES.ADMIN ? "Staff" : patient.firstName,
    role
  };
}

async function initializeAuthSession() {
  state.authError = "";
  if (!isAuthRequired()) {
    const role = getCurrentRole();
    state.currentUser = prototypeUserForRole(role);
    state.currentRole = role;
    state.authReady = true;
    return state.currentUser;
  }

  const session = loadAuthSession();
  if (session?.user && session?.idToken) {
    state.currentUser = session.user;
    state.currentRole = session.role || ROLES.PATIENT;
    state.authReady = true;
    return state.currentUser;
  }

  state.currentUser = null;
  state.currentRole = ROLES.PATIENT;
  state.authReady = true;
  return null;
}

async function signInWithEmailPassword(email, password) {
  state.authError = "";

  if (!isFirebaseMode()) {
    const role = String(email || "").toLowerCase().includes("admin") ? ROLES.ADMIN : ROLES.PATIENT;
    setCurrentRoleForPrototype(role);
    state.currentUser = prototypeUserForRole(role);
    saveAuthSession({ user: state.currentUser, role, idToken: "prototype-local-session" });
    return state.currentUser;
  }

  const response = await fetch(`https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${APP_CONFIG.firebase.apiKey}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email, password, returnSecureToken: true })
  });

  const result = await response.json();
  if (!response.ok) {
    state.authError = result?.error?.message || "Unable to sign in.";
    throw new Error(state.authError);
  }

  const role = await loadRoleForFirebaseUser(result.localId, result.idToken);
  state.currentUser = {
    uid: result.localId,
    email: result.email,
    firstName: result.displayName || result.email?.split("@")[0] || "Leaner patient"
  };
  state.currentRole = role;
  saveAuthSession({ user: state.currentUser, role, idToken: result.idToken, refreshToken: result.refreshToken });
  return state.currentUser;
}

async function loadRoleForFirebaseUser(uid, idToken) {
  try {
    const url = `https://firestore.googleapis.com/v1/projects/${APP_CONFIG.firebase.projectId}/databases/(default)/documents/users/${uid}`;
    const response = await fetch(url, { headers: { Authorization: `Bearer ${idToken}` } });
    if (!response.ok) return ROLES.PATIENT;
    const doc = await response.json();
    return doc?.fields?.role?.stringValue || ROLES.PATIENT;
  } catch {
    return ROLES.PATIENT;
  }
}

function signOut() {
  clearAuthSession();
  state.currentUser = null;
  state.currentRole = ROLES.PATIENT;
  state.authError = "";
  if (!isAuthRequired()) {
    state.currentUser = prototypeUserForRole(ROLES.PATIENT);
  }
}

function canAccessRoute(route) {
  if (!isAuthRequired()) return true;
  if (!state.authReady) return false;
  if (!state.currentUser) return route === ROUTES.LOGIN;
  if (route === ROUTES.LOGIN) return true;
  if (ADMIN_ROUTES.includes(route)) return isAdminRole();
  return true;
}
