(function (global) {
  "use strict";

  const state = { user: null, csrfToken: "", authenticated: false };

  function applySession(payload) {
    state.user = payload.user || null;
    state.csrfToken = payload.csrf_token || "";
    state.authenticated = Boolean(payload.authenticated);
    global.MobileAPI.setCsrfToken(state.csrfToken);
    return state;
  }

  async function me() {
    const payload = await global.MobileAPI.request("/api/auth/me");
    return applySession(payload);
  }

  async function login(username, password) {
    const payload = await global.MobileAPI.request("/api/auth/login", "POST", {
      username: username,
      password: password
    });
    return applySession(payload);
  }

  async function register(username, password) {
    const payload = await global.MobileAPI.request("/api/auth/register", "POST", {
      username: username,
      password: password
    });
    return applySession(payload);
  }

  async function logout() {
    try {
      await global.MobileAPI.request("/api/auth/logout", "POST", {});
    } finally {
      state.user = null;
      state.csrfToken = "";
      state.authenticated = false;
      global.MobileAPI.setCsrfToken("");
    }
  }

  function isAdmin() {
    return Boolean(state.user && state.user.role === "admin");
  }

  async function listAccounts() {
    return global.MobileAPI.request("/api/auth/accounts");
  }

  async function switchAccount(userId) {
    const payload = await global.MobileAPI.request("/api/auth/switch", "POST", {
      user_id: userId
    });
    return applySession(payload);
  }

  async function forgetAccount(userId) {
    await global.MobileAPI.request("/api/auth/forget", "POST", { user_id: userId });
  }

  global.MobileSession = {
    state: state,
    me: me,
    login: login,
    register: register,
    logout: logout,
    listAccounts: listAccounts,
    switchAccount: switchAccount,
    forgetAccount: forgetAccount,
    isAdmin: isAdmin
  };
})(window);
