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

const { setTokens, startAutoRefresh } = require("./token");
const { saveTokenData } = require("./tokenStore");

let accessToken = null;
let authServerStarted = false;

function startAuthServer() {
  if (authServerStarted) return;
  authServerStarted = true;

  const server = http.createServer(async (req, res) => {
    const url = new URL(req.url, "http://localhost:3000");

    if (url.pathname !== "/callback") return;

    const code = url.searchParams.get("code");

    if (!code) {
      res.writeHead(400);
      res.end("Missing OAuth code");
      return;
    }

    try {
      // Exchange code for tokens
      const tokenRes = await axios.post(
        "https://id.twitch.tv/oauth2/token",
        null,
        {
          params: {
            client_id: config.clientId,
            client_secret: config.clientSecret,
            code,
            grant_type: "authorization_code",
            redirect_uri: "http://localhost:3000/callback",
          },
        }
      );

      const access = tokenRes.data.access_token;
      const refresh = tokenRes.data.refresh_token;

      // Update runtime token system
      setTokens(access, refresh);
      startAutoRefresh();

      // Persist to disk
      saveTokenData({
        accessToken: access,
        refreshToken: refresh,
        savedAt: Date.now(),
      });

      accessToken = access;

      console.log("🔐 Twitch authentication successful");
      console.log("💾 Tokens saved to disk");

      res.writeHead(200, { "Content-Type": "text/plain" });
      res.end("Authentication successful. You can close this tab.");

    } catch (err) {
      console.error(
        "OAuth token exchange failed:",
        err.response?.data || err.message
      );

      res.writeHead(500);
      res.end("Authentication failed. Check terminal logs.");
    }
  });

  server.listen(3000, () => {
    const authUrl =
      "https://id.twitch.tv/oauth2/authorize" +
      `?client_id=${config.clientId}` +
      `&redirect_uri=http://localhost:3000/callback` +
      `&response_type=code` +
      `&scope=channel:read:redemptions`;

    console.log("\n👉 Twitch Login URL:\n");
    console.log(authUrl + "\n");
  });

  return {
    getToken: () => accessToken,
  };
}

module.exports = { startAuthServer };