// [TSM.ID].[11031972] -- All Rights Reserved. Proprietary & Confidential.
import { NextResponse } from 'next/server';
import { Pool } from 'pg';

const pool = new Pool({
  connectionString: process.env.DATABASE_URL || 'postgresql://jumpa_admin:JumpaS3cur3%21%40%23@127.0.0.1:5432/jumpadb',
});

export async function POST(req: Request) {
  try {
    const { room, pin, name } = await req.json();

    if (!room || !pin || !name) {
      return NextResponse.json({ error: 'Data tidak lengkap' }, { status: 400 });
    }

    // Cari tiket PIN yang belum dipakai dan belum expired (kita anggap belum expired kalau ada)
    const result = await pool.query(
      'SELECT id FROM guest_invites WHERE room = $1 AND pin = $2 AND is_used = false',
      [room, pin]
    );

    if (result.rows.length === 0) {
      return NextResponse.json({ error: 'PIN tidak valid atau sudah digunakan.' }, { status: 401 });
    }

    const pinId = result.rows[0].id;

    // PIN Valid! Kita kembalikan success. 
    // WebSocket di client akan mengirim sinyal 'guest_knock' setelah ini
    return NextResponse.json({ success: true, pinId }, { status: 200 });

  } catch (error) {
    console.error('[API GUEST KNOCK ERROR]', error);
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
  }
}
