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

let tokenCache = null;
let expiresAt = 0;

async function getAppToken() {
  const now = Date.now();

  // reuse token if still valid
  if (tokenCache && now < expiresAt) {
    return tokenCache;
  }

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

  tokenCache = res.data.access_token;
  expiresAt = now + res.data.expires_in * 1000 - 60000; // refresh 1 min early

  console.log("🔐 New Twitch App Token generated");

  return tokenCache;
}

module.exports = { getAppToken };