auth {
  mode: bearer
}

auth:bearer {
  token: {{access_token}}
}

vars:pre-request {
  current_profile: test-profile-0
}

script:pre-request {
  const axios = require("axios");
  const baseUrl = bru.getEnvVar("base_url");
  
  
  // Before each request, check and refresh access_token if needed.
  if (req.getAuthMode() === "bearer") {
    await checkAuth();
  }
  
  console.log("Testing GET /me");
  try {
    const resp = await axios.get(baseUrl + "/me", {headers: {"Authorization": "Bearer " + bru.getEnvVar("access_token")}});
  } catch (err) {
    console.log(err);
    console.log(err.stack);
  }
  
  
  async function checkAuth() {
    const access_token = bru.getEnvVar("access_token");
    if (!access_token || access_token === "null") {
      console.info("No access token is present, refreshing...");
      await refreshAuth();
      return;
    }
    // Access token exists, check that it's still valid.
    try {
      const resp = await axios.get(baseUrl + "/me", {
        headers: {"Authorization": "Bearer " + access_token}
      });
      if (resp.status === 200) {
        console.info("Current access token is valid.")
        return;
      } else if (resp.status === 401) {
        await refreshAuth();
      } else {
        throw resp;
      }
    } catch (error) {
      console.error(error);
    }
  }
  
  async function refreshAuth() {
    const payload = {
      username: bru.getEnvVar("username"),
      password: bru.getEnvVar("password")
    };
    const resp = await axios.post(baseUrl + "/login", payload, {
      headers: {"Content-Type": "application/json"}
    });
    if (resp.status === 200) {
      bru.setEnvVar("access_token", resp.data);
      console.info("Refreshed access token.");
    } else {
      throw resp;
    }
  }
  
}
