#!/usr/bin/env node

const GRAPH_API_VERSION = "v25.0";
const PSID = "27511427698460020";
const EXPECTED_ASID = "122111097783118257";
const APP_ID = "26934819589512827";
const PAGE_ACCESS_TOKEN = "EAAvjxLgXZB1YBRZCYO2s5qEQF4XeO6En1CfP6OZCfKZCEUwwbmwkKG3q0q4GNdZBPwxp3NF9ZATlSf0dN62I0fDErsJH8Iko5kUNbksh18QZAfQBxOwHoUyovMjZCrVzsN2lsglDOznqbHjMsv3d4XaNe4xWfyfpQdgffM3BXhTi2Nv7gZBf65LZBMlmqpNrZCTM0jXq2OAy6rV";

function assertConfigured(name, value) {
  if (!value || value.startsWith("TODO_")) {
    throw new Error(`Please fill script constant: ${name}`);
  }
}

async function main() {
  assertConfigured("PAGE_ACCESS_TOKEN", PAGE_ACCESS_TOKEN);

  const url = new URL(
    `https://graph.facebook.com/${GRAPH_API_VERSION}/${PSID}/ids_for_apps`,
  );
  url.searchParams.set("access_token", PAGE_ACCESS_TOKEN);

  const response = await fetch(url);
  const payload = await response.json();

  console.log(JSON.stringify(payload));

  if (payload.error) {
    console.error(`Graph API error: ${payload.error.message ?? "unknown"}`);
    process.exit(1);
  }

  if (!response.ok) {
    console.error(`Graph API request failed with HTTP ${response.status}.`);
    process.exit(1);
  }

  const matched = Array.isArray(payload.data)
    ? payload.data.find((item) => String(item?.app?.id ?? "") === APP_ID)
    : null;

  if (!matched?.id) {
    console.log(`Not found: no ASID record for app ${APP_ID}.`);
    process.exit(1);
  }

  const matchedAsid = String(matched.id);
  console.log(`Found ASID for app ${APP_ID}: ${matchedAsid}`);

  if (matchedAsid === EXPECTED_ASID) {
    console.log(`Matched: PSID maps to expected ASID ${EXPECTED_ASID}.`);
    return;
  }

  console.log(`Not matched: expected ASID ${EXPECTED_ASID}, got ${matchedAsid}.`);
  process.exit(1);
}

main().catch((error) => {
  console.error(error instanceof Error ? error.message : error);
  process.exit(1);
});
