const axios = require("axios");
const config = require("../config");

let accessToken = null;
let refreshToken = null;

function setTokens(initialAccess, initialRefresh) {
  accessToken = initialAccess;
  refreshToken = initialRefresh;
}

function getAccessToken() {
  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,
      },
    }
  );

  accessToken = res.data.access_token;
  refreshToken = res.data.refresh_token;

  console.log("🔄 Twitch token refreshed");

  return accessToken;
}

function startAutoRefresh() {
  // refresh every 3 hours (safe before expiry)
  setInterval(() => {
    refreshAccessToken().catch(console.error);
  }, 3 * 60 * 60 * 1000);
}

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