import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';

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

export async function POST(request: Request) {
  const payload = await request.json().catch(() => ({}));
  const label = typeof payload.label === 'string' ? payload.label : 'unknown';
  const utmAd = typeof payload.utmAd === 'string' && payload.utmAd ? payload.utmAd : undefined;

  const cookieStore = cookies();
  const sessionCookie = cookieStore.get(SESSION_COOKIE_NAME)?.value;
  const sessionData = parseSessionCookie(sessionCookie);
  const userId = sessionData?.userId ?? 'unknown';

  const adContext = utmAd ? `ad ${utmAd}` : 'ad unknown';
  const text = `Ayatique: user clicked ${label.trim().toLowerCase()} (${adContext}) (user ${userId})`;

  try {
    await sendTelegramMessage(text);
  } catch (error) {
    return NextResponse.json(
      { error: 'Telegram request failed', details: String(error) },
      { status: 502 }
    );
  }

  return NextResponse.json({ success: true }, { status: 200 });
}
