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

// Markiert einen Teilnehmer als inaktiv (is_active = 0). Zaehlt danach nicht mehr
// fuer die Match-Formel (2/3-Mehrheit bzw. beide-Ja-bei-2-Personen).
// Ist nach dem Verlassen NIEMAND mehr aktiv in der Session, wird die Session
// sofort komplett geloescht (inkl. Teilnehmer/Swipes/Vetos/Matches per ON DELETE
// CASCADE) statt auf den 48h-Cleanup-Job zu warten - eine verwaiste Session mit
// 0 aktiven Teilnehmern hat keinen Nutzen mehr und blockiert nur unnoetig Platz.
export async function POST(req: NextRequest, { params }: { params: Promise<{ code: string }> }) {
  const { code } = await params;
  const parsed = await parseBody(req, participantActionSchema);
  if (!parsed.success) return parsed.response;

  const { participantId } = parsed.data;
  const db = getDb();

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

  const participant = db.prepare(
    'SELECT * FROM participants WHERE id = ? AND session_id = ?'
  ).get(participantId, session.id) as any;
  if (!participant) return NextResponse.json({ error: 'Teilnehmer nicht gefunden' }, { status: 404 });

  db.prepare('UPDATE participants SET is_active = 0 WHERE id = ?').run(participantId);

  const remainingActive = db.prepare(
    'SELECT COUNT(*) as cnt FROM participants WHERE session_id = ? AND is_active = 1'
  ).get(session.id) as { cnt: number };

  let sessionDeleted = false;
  if (remainingActive.cnt === 0) {
    db.prepare('DELETE FROM sessions WHERE id = ?').run(session.id);
    sessionDeleted = true;
  }

  return NextResponse.json({ left: true, sessionDeleted });
}
