import { q as query } from '../../../chunks/db_Du3AmLCY.mjs';
import { g as generateClickRef, 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, shop_id, offer_id, source, source_detail, position } = body;
    if (!product_id || !shop_id || !source) {
      return new Response(JSON.stringify({ error: "Missing required fields" }), { status: 400 });
    }
    const clickRef = generateClickRef();
    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") || "";
    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 click_events (click_ref, product_id, shop_id, offer_id, session_id, source, source_detail, position, user_agent, ip_hash, referrer, utm_source, utm_medium, utm_campaign)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)`,
      [
        clickRef,
        product_id,
        shop_id,
        offer_id || null,
        sessionId,
        source,
        source_detail || null,
        position || null,
        request.headers.get("user-agent"),
        hashIP(ip),
        referer,
        utmSource,
        utmMedium,
        utmCampaign
      ]
    );
    let redirectUrl = `/api/redirect/${offer_id || product_id}?ref=${clickRef}`;
    if (offer_id) {
      try {
        const result = await query("SELECT affiliate_url, network FROM offers WHERE id = $1 LIMIT 1", [offer_id]);
        if (result.rows.length) {
          const offer = result.rows[0];
          const url = new URL(offer.affiliate_url);
          if (offer.network === "webgains") url.searchParams.set("clickRef", clickRef);
          else if (offer.network === "tradetracker") url.searchParams.set("r", clickRef);
          else url.searchParams.set("subid", clickRef);
          redirectUrl = url.toString();
        }
      } catch {
      }
    }
    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({ redirect_url: redirectUrl, click_ref: clickRef }), { headers });
  } catch (err) {
    console.error("Click 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 };
