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

let accessToken = null;

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

    if (url.pathname === "/callback") {
      const code = url.searchParams.get("code");

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

      try {
        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",
            },
          }
        );

        accessToken = tokenRes.data.access_token;

        console.log("🔐 Twitch user token acquired!");

        res.end("Auth successful! You can close this tab.");

      } catch (err) {
        console.error(err.response?.data || err.message);
        res.end("Auth failed");
      }
    }
  });

  server.listen(3000, () => {
    console.log("\n👉 Open this URL to login:\n");

    const url =
      `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(url + "\n");
  });

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

module.exports = { startAuthServer };