import { NextRequest, NextResponse } from 'next/server' import { isSupabaseConfigured } from 'lib/supabase/server' import { verifyPin } from 'lib/codes' import { getCodeByCode, getCodeForUserInRoom, updateCode } from 'lib/persistence' import { logEvent } from 'lib/logger' import { getAppSession } from 'lib/appSession' export async function POST(request: NextRequest) { try { const body = await request.json() const { code, pin } = body if (!code) { return NextResponse.json({ error: 'Chybí kód' }, { status: 400 }) } if (!isSupabaseConfigured()) { return NextResponse.json( { error: 'Supabase not configured (missing NEXT_PUBLIC_SUPABASE_URL / NEXT_PUBLIC_SUPABASE_ANON_KEY)' }, { status: 503 } ) } const session = await getAppSession() if (!session) { return NextResponse.json({ error: 'Neautorizován' }, { status: 401 }) } const codeData = await getCodeByCode(code) if (!codeData || codeData.used !== 1 || codeData.user_id !== null) { return NextResponse.json({ error: 'Kód nenalezen nebo už je přiřazen k účtu' }, { status: 404 }) } if (!codeData.room_id) { return NextResponse.json({ error: 'Kód nemá přiřazenou místnost' }, { status: 400 }) } const existingCode = await getCodeForUserInRoom(codeData.room_id, session.userId) if (existingCode) { return NextResponse.json({ error: 'Tuto místnost už máte ve svém profilu' }, { status: 409 }) } if (codeData.pin_hash) { if (!pin) { return NextResponse.json({ error: 'Kód je chráněn PIN', needsPin: true }, { status: 400 }) } const isValidPin = await verifyPin(pin, codeData.pin_hash) if (!isValidPin) { return NextResponse.json({ error: 'Neplatný PIN' }, { status: 401 }) } } const updated = await updateCode(codeData.id, { user_id: session.userId, session_hash: null }) if (!updated) { console.error('Error transferring code: update failed') return NextResponse.json({ error: 'Nepodařilo se převést kód' }, { status: 500 }) } await logEvent({ module: 'codes', operation: 'transfer_to_user', data: { codeId: codeData.id, userId: session.userId, roomId: codeData.room_id }, ip: (request as any).headers?.get?.('x-forwarded-for') || null, userAgent: (request as any).headers?.get?.('user-agent') || null }) return NextResponse.json({ success: true, message: 'Kód byl úspěšně převeden do vašeho profilu' }) } catch (error) { console.error('Transfer code error:', error) return NextResponse.json({ error: 'Vnitřní chyba serveru' }, { status: 500 }) } }