import { trackSiteEvent } from "../_shared/stats.js";

export async function onRequestPost(context) {
  const payload = await parsePayload(context.request);
  const eventType = payload?.eventType === "page_view" ? "page_view" : "";
  if (!eventType) {
    return json({ ok: false, error: "invalid_event_type" }, 400);
  }

  await trackSiteEvent(context.env, context.request, eventType, {
    pagePath: payload?.pagePath || "/"
  });

  return json({ ok: true });
}

async function parsePayload(request) {
  const contentType = request.headers.get("content-type") || "";
  if (contentType.includes("application/json")) {
    try {
      return await request.json();
    } catch (error) {
      return {};
    }
  }

  const text = await request.text();
  if (!text) {
    return {};
  }

  try {
    return JSON.parse(text);
  } catch (error) {
    return {};
  }
}

function json(data, status = 200) {
  return new Response(JSON.stringify(data, null, 2), {
    status,
    headers: {
      "content-type": "application/json; charset=utf-8",
      "cache-control": "no-store"
    }
  });
}
