import { NextRequest, NextResponse } from 'next/server';
import { randomUUID } from 'crypto';

import pool from '../../../lib/db';
import {
  parseSessionCookie,
  serializeSessionData,
  SESSION_COOKIE_NAME,
} from '../../../lib/session';
import { sendTikTokServerEvent } from '../../../lib/tiktokServer';
import { SECTION_ORDER } from '../../onboarding/sectionConfig';

const LAST_INDEX = SECTION_ORDER.length - 1;
const FINAL_STEP = SECTION_ORDER[LAST_INDEX];

function calculateProgress(page: string): number {
  const idx = SECTION_ORDER.indexOf(page);
  if (idx === -1) return 0;
  return Math.round((idx / LAST_INDEX) * 100);
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json().catch(() => ({}));
    const { page, status, plan, ttEvents } = body as {
      page?: string;
      status?: string;
      plan?: string;
      ttEvents?: Array<{
        eventName: string;
        eventId: string;
        contentId?: string;
        contentName?: string;
      }>;
    };

    const cookieValue = request.cookies.get(SESSION_COOKIE_NAME)?.value;
    const session = parseSessionCookie(cookieValue);
    if (!session.userId) {
      session.userId = randomUUID();
    }
    const userId = session.userId;

    if (page) {
      const progress = calculateProgress(page);
      const utmAd = session.utmAd ?? null;

      const resolvedStatus =
        status === 'purchased'
          ? 'purchased'
          : page === FINAL_STEP
            ? 'completed'
            : 'in_progress';

      const resolvedPlan = plan ?? null;

      await pool.execute(
        `INSERT INTO onboarding_users (id, current_page, progress, status, plan, utm_ad)
         VALUES (?, ?, ?, ?, ?, ?)
         ON DUPLICATE KEY UPDATE
           current_page = IF(VALUES(progress) >= progress, VALUES(current_page), current_page),
           progress     = GREATEST(progress, VALUES(progress)),
           status       = CASE
                            WHEN VALUES(status) = 'purchased' THEN 'purchased'
                            WHEN status = 'purchased' THEN 'purchased'
                            WHEN VALUES(status) = 'completed' THEN 'completed'
                            WHEN status = 'completed' AND VALUES(status) = 'in_progress' THEN 'completed'
                            ELSE VALUES(status)
                          END,
           plan         = COALESCE(VALUES(plan), plan),
           utm_ad       = COALESCE(utm_ad, VALUES(utm_ad))`,
        [userId, page, progress, resolvedStatus, resolvedPlan, utmAd],
      );

      session.choices[page] = status ?? 'visited';
      session.updatedAt = new Date().toISOString();
    }

    if (ttEvents?.length) {
      const ip =
        request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ??
        request.headers.get('x-real-ip') ??
        '0.0.0.0';
      const userAgent = request.headers.get('user-agent') ?? '';
      const referer = request.headers.get('referer') ?? '';

      for (const ev of ttEvents) {
        sendTikTokServerEvent({
          eventName: ev.eventName,
          eventId: ev.eventId,
          ip,
          userAgent,
          url: referer,
          contentId: ev.contentId,
          contentName: ev.contentName,
        }).catch(() => {});
      }
    }

    const response = NextResponse.json({ ok: true });
    response.cookies.set(SESSION_COOKIE_NAME, serializeSessionData(session), {
      path: '/',
      httpOnly: true,
      sameSite: 'lax',
      maxAge: 60 * 60 * 24,
    });
    return response;
  } catch (error) {
    console.error('Track API error:', error);
    return NextResponse.json({ error: 'Internal error' }, { status: 500 });
  }
}
