/* eslint-disable */
// [TSM.ID].[11031972] -- All Rights Reserved. Proprietary & Confidential.
import { NextResponse } from 'next/server';
import { Pool } from 'pg';
import jwt from 'jsonwebtoken';
import { cookies } from 'next/headers';

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 cookieStore = await cookies();
    const token = cookieStore.get('jumpa_token')?.value;

    if (!token) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    let decoded: any;
    try {
      decoded = jwt.verify(token, process.env.JWT_SECRET as string);
    } catch (e) {
      return NextResponse.json({ error: 'Invalid Token' }, { status: 401 });
    }

    const { room } = await req.json();
    if (!room) {
      return NextResponse.json({ error: 'Room is required' }, { status: 400 });
    }

    // Generate 6-digit random PIN dengan Kriptografi Node.js
    const pin = (crypto.getRandomValues(new Uint32Array(1))[0] % 900000 + 100000).toString();

    // Insert into guest_invites
    await pool.query(
      'INSERT INTO guest_invites (room, host_id, pin) VALUES ($1, $2, $3)',
      [room, decoded.email, pin]
    );

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

