#!/usr/bin/env node
/**
 * Quick script to check SIM status in Freebit
 * Usage: node scripts/check-sim-status.mjs <phone_number>
 */

const account = process.argv[2] || "02000002470010";

const FREEBIT_BASE_URL = "https://i1-q.mvno.net/emptool/api";
const FREEBIT_OEM_ID = "PASI";
const FREEBIT_OEM_KEY = "6Au3o7wrQNR07JxFHPmf0YfFqN9a31t5";

async function getAuthKey() {
  const request = {
    oemId: FREEBIT_OEM_ID,
    oemKey: FREEBIT_OEM_KEY,
  };

  const response = await fetch(`${FREEBIT_BASE_URL}/authOem/`, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: `json=${JSON.stringify(request)}`,
  });

  if (!response.ok) {
    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
  }

  const data = await response.json();
  if (data.resultCode !== 100 && data.resultCode !== "100") {
    throw new Error(`Auth failed: ${data.status?.message || JSON.stringify(data)}`);
  }

  return data.authKey;
}

async function getTrafficInfo(authKey, account) {
  const request = { authKey, account };

  const response = await fetch(`${FREEBIT_BASE_URL}/mvno/getTrafficInfo/`, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: `json=${JSON.stringify(request)}`,
  });
  return response.json();
}

async function getAccountDetails(authKey, account) {
  const request = {
    authKey,
    version: "2",
    requestDatas: [{ kind: "MVNO", account }],
  };

  const response = await fetch(`${FREEBIT_BASE_URL}/master/getAcnt/`, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: `json=${JSON.stringify(request)}`,
  });
  return response.json();
}

async function main() {
  console.log(`\n🔍 Checking SIM status for: ${account}\n`);

  try {
    const authKey = await getAuthKey();
    console.log("✓ Authenticated with Freebit\n");

    // Try getTrafficInfo first (simpler)
    console.log("--- Traffic Info (/mvno/getTrafficInfo/) ---");
    const trafficInfo = await getTrafficInfo(authKey, account);
    console.log(JSON.stringify(trafficInfo, null, 2));

    // Try getAcnt for full details
    console.log("\n--- Account Details (/master/getAcnt/) ---");
    const details = await getAccountDetails(authKey, account);
    console.log(JSON.stringify(details, null, 2));
  } catch (error) {
    console.error("❌ Error:", error.message);
  }
}

main();
