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

export const POST: APIRoute = 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]
    );

    // Build redirect URL - for now return a placeholder
    // In production, look up the offer's affiliate URL and append clickRef
    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: 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({ 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 });
  }
};
