const axios = require("axios");
const config = require("../config");
const { getAppToken } = require("./auth");

async function createSubscription(sessionId) {
  try {
    const token = await getAppToken();

    await axios.post(
      "https://api.twitch.tv/helix/eventsub/subscriptions",
      {
        type: "channel.channel_points_custom_reward_redemption.add",
        version: "1",
        condition: {
          broadcaster_user_id: config.broadcasterId,
        },
        transport: {
          method: "websocket",
          session_id: sessionId,
        },
      },
      {
        headers: {
          "Client-ID": config.clientId,
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
        },
      }
    );

    console.log("📡 Subscription created");
  } catch (err) {
    console.error(
      "❌ Subscription error:",
      err.response?.data || err.message
    );
  }
}

module.exports = { createSubscription };