import { NextRequest, NextResponse } from 'next/server';
import { getDb } from '@/lib/db';
import { randomUUID } from 'crypto';
import { joinSessionSchema, parseBody } from '@/lib/validation';

export async function POST(req: NextRequest, { params }: { params: Promise<{ code: string }> }) {
  const { code } = await params;
  const parsed = await parseBody(req, joinSessionSchema);
  if (!parsed.success) return parsed.response;

  const { displayName, anonymousId: clientAnonymousId } = parsed.data;
  const db = getDb();

  const session = db.prepare("SELECT * FROM sessions WHERE code = ? AND status = 'active'").get(code);
  if (!session) {
    return NextResponse.json({ error: 'Session nicht gefunden oder beendet' }, { status: 404 });
  }

  // BUGFIX/FEATURE: anonymousId wird jetzt vom Client wiederverwendet, falls
  // das Geraet schon eine kennt (LocalStorage yumder_anonymous_id aus einem
  // fruehreren Besuch). Vorher wurde bei JEDEM Beitritt eine neue randomUUID()
  // erzeugt, unabhaengig davon, ob das Geraet bereits eine hatte - dadurch
  // war es unmoeglich, dieselbe Person ueber mehrere Sessions hinweg zu
  // erkennen (Grundvoraussetzung fuer die Wiederkehrer-Rate im Admin-
  // Dashboard, siehe lib/retention.ts). Ein simples String-Format-Check
  // reicht hier - kein Sicherheitsrisiko, da anonymous_id nur zur Analyse
  // dient und keine Berechtigung ueber sie erteilt wird.
  const isValidUuid = typeof clientAnonymousId === 'string' && /^[0-9a-f-]{36}$/i.test(clientAnonymousId);
  const anonymousId = isValidUuid ? clientAnonymousId : randomUUID();

  const participant = db.prepare(`
    INSERT INTO participants (session_id, anonymous_id, display_name, is_creator)
    VALUES (?, ?, ?, 0)
  `).run((session as any).id, anonymousId, displayName ?? null);

  return NextResponse.json({
    sessionId: (session as any).id,
    anonymousId,
    participantId: participant.lastInsertRowid,
  });
}
