const AFFILIATE_LINKS = {
  "base-bridge": "https://bridge.base.org/",
  "basescan-gas": "https://basescan.org/gastracker",
  "coinbase-wallet": "https://www.coinbase.com/wallet"
};

const CORS_HEADERS = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type"
};

async function forwardToGas(env, record) {
  if (!env.GAS_WEBHOOK_URL) return;
  try {
    await fetch(env.GAS_WEBHOOK_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(record)
    });
  } catch (_) {}
}

async function getTxReceipt(txHash) {
  const res = await fetch("https://mainnet.base.org", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      jsonrpc: "2.0",
      id: 1,
      method: "eth_getTransactionReceipt",
      params: [txHash]
    })
  });
  const data = await res.json();
  return data ? data.result : null;
}

export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);

    if (request.method === "OPTIONS") {
      return new Response(null, { status: 204, headers: CORS_HEADERS });
    }

    // Tracked outbound click route: /go/<slug>
    if (request.method === "GET" && url.pathname.startsWith("/go/")) {
      const slug = decodeURIComponent(url.pathname.slice(4));
      const targetUrl = AFFILIATE_LINKS[slug];
      if (!targetUrl) {
        return new Response("Unknown link slug", { status: 404, headers: CORS_HEADERS });
      }

      const clickRecord = {
        type: "outbound_click",
        slug,
        visitorId: url.searchParams.get("vid") || "",
        country: request.cf?.country || "",
        ts: new Date().toISOString()
      };
      ctx.waitUntil(forwardToGas(env, clickRecord));

      return Response.redirect(targetUrl, 302);
    }

    // Telemetry & tx verification endpoint: POST /api/track
    if (request.method === "POST" && url.pathname === "/api/track") {
      let body = {};
      try {
        body = await request.json();
      } catch (_) {
        return new Response(JSON.stringify({ ok: false, error: "Invalid JSON" }), {
          status: 400,
          headers: { ...CORS_HEADERS, "Content-Type": "application/json" }
        });
      }

      let verifiedStatus = "n/a";
      if (body.event === "crypto_tx" && typeof body.txHash === "string" && /^0x[a-fA-F0-9]{64}$/.test(body.txHash)) {
        const receipt = await getTxReceipt(body.txHash);
        verifiedStatus = receipt ? (receipt.status === "0x1" ? "confirmed" : "reverted") : "pending";
      }

      const eventRecord = {
        type: "telemetry",
        event: String(body.event || "unknown"),
        visitorId: String(body.visitorId || ""),
        wallet: String(body.wallet || ""),
        slug: String(body.slug || ""),
        asset: String(body.asset || ""),
        amount: Number(body.amount || 0),
        purpose: String(body.purpose || ""),
        txHash: String(body.txHash || ""),
        txStatus: verifiedStatus,
        country: request.cf?.country || "",
        path: String(body.path || "/"),
        ts: String(body.ts || new Date().toISOString())
      };

      ctx.waitUntil(forwardToGas(env, eventRecord));

      return new Response(JSON.stringify({ ok: true, txStatus: verifiedStatus }), {
        status: 200,
        headers: { ...CORS_HEADERS, "Content-Type": "application/json" }
      });
    }

    return new Response("Not Found", { status: 404, headers: CORS_HEADERS });
  }
};