export type UserSession = {
  id: string;
  email: string;
  role: string | null;
  permissions: string[];
};

class AuthService {
  private _user: UserSession | null = null;
  private _accessToken: string | null = null;
  private _teamCode: string | null = null;

  init() {
    const stored = sessionStorage.getItem("session");
    if (stored) this._user = JSON.parse(stored);
    this._teamCode = sessionStorage.getItem("team_code");
  }

  get user() {
    return this._user;
  }
  get isLoggedIn() {
    return this._accessToken !== null;
  }
  get isAdmin() {
    return this._user?.role === "admin";
  }
  get accessToken() {
    return this._accessToken;
  }

  get hasTeamCode() {
    return this._teamCode !== null;
  }
  get teamCode() {
    return this._teamCode;
  }

  setSession(user: UserSession, accessToken: string) {
    if (user == undefined || accessToken == undefined) {
      console.warn("not saving undefined session");
      return;
    }
    this._user = user;
    this._accessToken = accessToken;
    sessionStorage.setItem("session", JSON.stringify(user));
  }

  setTeamCode(code: string) {
    this._teamCode = code;
    sessionStorage.setItem("team_code", code);
  }

  clearTeamCode() {
    this._teamCode = null;
    sessionStorage.removeItem("team_code");
  }

  clearSession() {
    this._user = null;
    this._accessToken = null;
    this._teamCode = null;
    sessionStorage.clear();
  }

  hasPermission(permission: string) {
    return this._user?.permissions.includes(permission) ?? false;
  }
}

export const authService = new AuthService();
