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

import {
  parseSessionCookie,
  serializeSessionData,
  SESSION_COOKIE_NAME,
} from '../../../lib/session';
import { sendTelegramMessage } from '../../../lib/telegram';

const NOTIFICATION_TTL_MS = 60 * 1000;
const notifiedUsers = new Set<string>();

const markNotified = (userId: string) => {
  notifiedUsers.add(userId);
  setTimeout(() => notifiedUsers.delete(userId), NOTIFICATION_TTL_MS);
};

export async function POST(request: NextRequest) {
  const payload = await request.json().catch(() => ({}));
  const { step, choice, utmAd } = payload as {
    step?: string;
    choice?: unknown;
    utmAd?: unknown;
  };

  if (!step) {
    return NextResponse.json({ error: 'Missing step' }, { status: 400 });
  }

  const cookieValue = request.cookies.get(SESSION_COOKIE_NAME)?.value;
  const sessionData = parseSessionCookie(cookieValue);

  if (!sessionData.userId) {
    sessionData.userId = randomUUID();
  }

  const previousChoice = sessionData.choices[step];
  sessionData.choices[step] = choice;
  sessionData.updatedAt = new Date().toISOString();
  if (typeof utmAd === 'string' && utmAd) {
    sessionData.utmAd = sessionData.utmAd ?? utmAd;
  }

  const userId = sessionData.userId;

  if (
    (step === 'plans' || step === 'plansone') &&
    choice === 'visited' &&
    previousChoice !== 'visited' &&
    userId &&
    !notifiedUsers.has(userId)
  ) {
    try {
      const adContext = sessionData.utmAd ? `ad ${sessionData.utmAd}` : 'ad unknown';
      await sendTelegramMessage(
        `Ayatique onboarding complete for user ${userId} (${adContext})`
      );
      markNotified(userId);
    } catch (error) {
      console.error('Failed to notify onboarding completion', error);
    }
  }

  const response = NextResponse.json({ status: 'ok', session: sessionData });
  response.cookies.set(SESSION_COOKIE_NAME, serializeSessionData(sessionData), {
    path: '/',
    httpOnly: true,
    sameSite: 'lax',
    maxAge: 60 * 60 * 24,
  });

  return response;
}
