const axios = require("axios");
const config = require("../config");
const { saveTokenData, loadTokenData } = require("./tokenStore");

let accessToken = null;
let refreshToken = null;

function initFromDisk() {
  const data = loadTokenData();

  if (!data) return false;

  accessToken = data.accessToken;
  refreshToken = data.refreshToken;

  console.log("💾 Loaded token from disk");
  return true;
}

function setTokens(at, rt) {
  accessToken = at;
  refreshToken = rt;

  saveTokenData({
    accessToken,
    refreshToken,
    savedAt: Date.now(),
  });
}

function getAccessToken() {
  if (!accessToken) throw new Error("Token not ready");
  return accessToken;
}

async function refreshAccessToken() {
  if (!refreshToken) return;

  const res = await axios.post(
    "https://id.twitch.tv/oauth2/token",
    null,
    {
      params: {
        grant_type: "refresh_token",
        refresh_token: refreshToken,
        client_id: config.clientId,
        client_secret: config.clientSecret,
      },
    }
  );

  setTokens(res.data.access_token, res.data.refresh_token);

  console.log("🔄 Token refreshed + saved");
}

function startAutoRefresh() {
  setInterval(() => {
    refreshAccessToken().catch(console.error);
  }, 3 * 60 * 60 * 1000);
}

module.exports = {
  setTokens,
  getAccessToken,
  startAutoRefresh,
  initFromDisk,
};