const http = require("http");
const axios = require("axios");
const config = require("../config");
const { setTokens, startAutoRefresh } = require("./token");

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");

    // OAuth callback endpoint
    if (url.pathname === "/callback") {
      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 accessToken = tokenRes.data.access_token;
        const refreshToken = tokenRes.data.refresh_token;
        const expiresIn = tokenRes.data.expires_in;

        // Store tokens globally in auth system
        setTokens(accessToken, refreshToken);

        // Start auto-refresh loop
        startAutoRefresh();

        console.log("🔐 Twitch authentication successful");
        console.log(`⏱ Token expires in: ${expiresIn}s`);

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

      } 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:");
    console.log(authUrl + "\n");
  });
}

module.exports = { startAuthServer };