#!/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";
const APP_SECRET = "004b1a9384b3433e153992e5edcef4ad";

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

async function createAppSecretProof(accessToken, appSecret) {
  const { createHmac } = await import("node:crypto");
  return createHmac("sha256", appSecret.trim())
    .update(accessToken.trim())
    .digest("hex");
}

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

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

  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.some((item) => item && String(item.id) === EXPECTED_ASID)
    : false;

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

  console.log(`Not matched: PSID does not map to ASID ${EXPECTED_ASID}.`);
  process.exit(1);
}

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