/**
 * levelCheck.js — Verifica en vivo qué paquetes de Aumento de Nivel
 * tiene disponibles un jugador, consultando la región SV de Garena.
 *
 * Usa la misma cookie que el flujo DO. Si DataDome bloquea, lo reporta
 * sin romper nada. Devuelve { availableLevels: [6, 10, ...] } o error tipado.
 */

import fs from 'fs';
import { GARENA, COOKIE_FILE, USER_AGENT } from '../config.js';
import { readSavedCookies } from './garena.js';

const __commonHeaders = {
  Origin: GARENA.baseUrl,
  Referer: `${GARENA.baseUrl}/app/${GARENA.appId}`,
  Accept: 'application/json, text/plain, */*',
  'User-Agent': USER_AGENT,
  'Sec-CH-UA': '"Not A;Brand";v="99", "Chromium";v="120", "Google Chrome";v="120"',
  'Sec-CH-UA-Mobile': '?0',
  'Sec-CH-UA-Platform': '"Windows"',
  'Sec-Fetch-Dest': 'empty',
  'Sec-Fetch-Mode': 'cors',
  'Sec-Fetch-Site': 'same-origin',
  'Accept-Language': 'es-ES,es;q=0.9',
};

function cookieHeaderFromMap(map) {
  return [...map].map(([name, value]) => `${name}=${value}`).join('; ');
}

function applySetCookies(resp, map) {
  const setCookies = typeof resp.headers.getSetCookie === 'function'
    ? resp.headers.getSetCookie()
    : (resp.headers.get('set-cookie') ? [resp.headers.get('set-cookie')] : []);
  for (const sc of setCookies) {
    const [pair] = sc.split(';');
    const idx = pair.indexOf('=');
    if (idx > 0) map.set(pair.slice(0, idx).trim(), pair.slice(idx + 1));
  }
}

export async function checkLevelAvailability(playerId) {
  if (!fs.existsSync(COOKIE_FILE)) return { ok: false, reason: 'no_cookie' };

  const savedCookies = readSavedCookies();
  const cookieMap = new Map(savedCookies.map(c => [c.name, c.value]));
  cookieMap.delete('session_key');

  // Login para generar session_key fresco
  let loginResp;
  try {
    loginResp = await fetch(GARENA.loginUrl, {
      method: 'POST',
      headers: {
        ...__commonHeaders,
        Cookie: cookieHeaderFromMap(cookieMap),
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ app_id: GARENA.appId, login_id: playerId, app_server_id: 0 }),
    });
  } catch (_e) {
    return { ok: false, reason: 'network' };
  }

  if (loginResp.status === 403) return { ok: false, reason: 'datadome' };
  if (!loginResp.ok) return { ok: false, reason: `login_status_${loginResp.status}` };

  applySetCookies(loginResp, cookieMap);

  // GET channels región SV
  const svUrl = `${GARENA.baseUrl}/api/shop/apps/channels?app_id=${GARENA.appId}&packed_role_id=0&region=SV&language=es`;
  let svResp;
  try {
    svResp = await fetch(svUrl, {
      method: 'GET',
      headers: { ...__commonHeaders, Cookie: cookieHeaderFromMap(cookieMap) },
    });
  } catch (_e) {
    return { ok: false, reason: 'network_sv' };
  }

  if (!svResp.ok) return { ok: false, reason: `sv_status_${svResp.status}` };

  const svData = await svResp.json();
  const availableLevels = [];

  for (const ch of svData?.channels || []) {
    for (const item of ch.items || []) {
      const name = String(item.name || '');
      if (!name.includes('Aumento de Nivel') && !name.includes('aumento de nivel')) continue;
      const m = name.match(/Nivel\s*(\d+)/i);
      if (m) {
        const lvl = Number(m[1]);
        if (!availableLevels.includes(lvl)) availableLevels.push(lvl);
      }
    }
  }

  // rebate_card a nivel raíz del JSON
  if (svData?.rebate_card) {
    const m = String(svData.rebate_card.name || '').match(/Nivel\s*(\d+)/i);
    if (m) {
      const lvl = Number(m[1]);
      if (!availableLevels.includes(lvl)) availableLevels.push(lvl);
    }
  }

  availableLevels.sort((a, b) => a - b);
  return { ok: true, availableLevels };
}
