/**
 * Server-side TikTok Events API.
 *
 * Sends events to https://business-api.tiktok.com/open_api/v1.3/event/track/
 * Uses the same event_id as the browser pixel so TikTok can deduplicate.
 */

const TIKTOK_API_URL = 'https://business-api.tiktok.com/open_api/v1.3/event/track/';

interface TikTokServerEvent {
  eventName: string;
  eventId: string;
  ip: string;
  userAgent: string;
  url?: string;
  contentId?: string;
  contentName?: string;
}

export async function sendTikTokServerEvent(event: TikTokServerEvent) {
  const accessToken = process.env.TIKTOK_ACCESS_TOKEN?.trim();
  const pixelId = process.env.NEXT_PUBLIC_TIKTOK_PIXEL_ID?.trim();

  if (!accessToken || !pixelId) return;

  const payload = {
    event_source: 'web',
    event_source_id: pixelId,
    data: [
      {
        event: event.eventName,
        event_time: Math.floor(Date.now() / 1000),
        event_id: event.eventId,
        user: {
          user_agent: event.userAgent,
          ip: event.ip,
        },
        page: {
          url: event.url,
        },
        properties: {
          content_id: event.contentId,
          content_name: event.contentName,
        },
      },
    ],
  };

  try {
    const response = await fetch(TIKTOK_API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Access-Token': accessToken,
      },
      body: JSON.stringify(payload),
    });

    if (!response.ok) {
      const text = await response.text();
      console.error('TikTok Events API error:', response.status, text);
    }
  } catch (error) {
    console.error('TikTok Events API request failed:', error);
  }
}
