import type { APIRoute } from 'astro';
import { query } from '../../../lib/db';
import { hashIP } from '../../../lib/tracking';
import { parseCookies } from '../../../lib/auth';

export const POST: APIRoute = 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: Record<string, string> = { '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 });
  }
};
