import { q as query } from '../../../chunks/db_Du3AmLCY.mjs';
import { h as hashIP } from '../../../chunks/tracking_C2sKJNTK.mjs';
import { p as parseCookies } from '../../../chunks/auth_C2RFIYRJ.mjs';
export { renderers } from '../../../renderers.mjs';

const POST = async ({ request }) => {
  try {
    const body = await request.json();
    const { product_id, page_type } = body;
    if (!page_type) {
      return new Response(JSON.stringify({ error: "Missing page_type" }), { status: 400 });
    }
    const cookies = parseCookies(request.headers.get("cookie"));
    const sessionId = cookies.sp_sid || crypto.randomUUID();
    const ip = request.headers.get("x-forwarded-for") || request.headers.get("x-real-ip") || "";
    const referer = request.headers.get("referer") || "";
    const ua = request.headers.get("user-agent") || "";
    let utmSource = null, utmMedium = null, utmCampaign = null;
    try {
      const refUrl = new URL(referer);
      utmSource = refUrl.searchParams.get("utm_source");
      utmMedium = refUrl.searchParams.get("utm_medium");
      utmCampaign = refUrl.searchParams.get("utm_campaign");
    } catch {
    }
    await query(
      `INSERT INTO page_views (product_id, page_type, session_id, ip_hash, user_agent, referrer, utm_source, utm_medium, utm_campaign)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
      [product_id || null, page_type, sessionId, hashIP(ip), ua, referer, utmSource, utmMedium, utmCampaign]
    );
    const headers = { "Content-Type": "application/json" };
    if (!cookies.sp_sid) {
      headers["Set-Cookie"] = `sp_sid=${sessionId}; Path=/; Max-Age=${30 * 86400}; SameSite=Lax`;
    }
    return new Response(JSON.stringify({ ok: true }), { headers });
  } catch (err) {
    console.error("Pageview tracking error:", err);
    return new Response(JSON.stringify({ error: "Internal error" }), { status: 500 });
  }
};

const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
  __proto__: null,
  POST
}, Symbol.toStringTag, { value: 'Module' }));

const page = () => _page;

export { page };
