const JACKBOX_API_BASE = 'https://ecast.jackboxgames.com/api/v2';

const DEFAULT_HEADERS = {
  'User-Agent': 'Mozilla/5.0 (compatible; GamePicker/1.0)'
};

/**
 * Check room status via the Jackbox ecast REST API.
 * Shared by room-monitor (polling for lock) and player-count-checker (room existence).
 */
async function checkRoomStatus(roomCode) {
  try {
    const response = await fetch(`${JACKBOX_API_BASE}/rooms/${roomCode}`, {
      headers: DEFAULT_HEADERS
    });

    if (!response.ok) {
      console.log(`[Jackbox API] Room ${roomCode}: HTTP ${response.status}`);
      return { exists: false };
    }

    const data = await response.json();
    const roomData = data.body || data;

    if (process.env.DEBUG === 'true') {
      console.log('[Jackbox API] Room data:', JSON.stringify(roomData, null, 2));
    }

    return {
      exists: true,
      locked: roomData.locked || false,
      full: roomData.full || false,
      maxPlayers: roomData.maxPlayers || 8,
      minPlayers: roomData.minPlayers || 0
    };
  } catch (e) {
    console.error(`[Jackbox API] Error checking room ${roomCode}:`, e.message);
    return { exists: false };
  }
}

async function getRoomInfo(roomCode) {
  try {
    const response = await fetch(`${JACKBOX_API_BASE}/rooms/${roomCode}`, {
      headers: DEFAULT_HEADERS
    });

    if (!response.ok) {
      console.log(`[Jackbox API] Room ${roomCode}: HTTP ${response.status}`);
      return { exists: false };
    }

    const data = await response.json();
    const body = data.body || data;

    return {
      exists: true,
      host: body.host,
      audienceHost: body.audienceHost,
      appTag: body.appTag,
      appId: body.appId,
      code: body.code,
      locked: body.locked || false,
      full: body.full || false,
      maxPlayers: body.maxPlayers || 8,
      minPlayers: body.minPlayers || 0,
      audienceEnabled: body.audienceEnabled || false,
    };
  } catch (e) {
    console.error(`[Jackbox API] Error getting room info for ${roomCode}:`, e.message);
    return { exists: false };
  }
}

module.exports = { checkRoomStatus, getRoomInfo };
