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

// Klien Redis untuk Publisher
const redisUrl = process.env.REDIS_URL || "redis://localhost:6379";
const redis = new Redis(redisUrl);

// Koneksi ke PostgreSQL VPS
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: NextRequest) {
  try {
    const body = await req.json();
    const { channel, event, payload } = body;

    if (!channel || !event) {
      return NextResponse.json({ error: "Missing channel or event" }, { status: 400 });
    }

    // Tangani logika khusus DB jika event adalah host_approve_guest
    if (event === "host_approve_guest") {
        try {
            await pool.query('UPDATE guest_invites SET is_used = true WHERE id = $1', [payload.pinId]);
        } catch (e) {
            console.error('[DB Error] Failed to approve guest:', e);
        }
    }

    const message = JSON.stringify({ event, payload, timestamp: Date.now() });

    // Pancarkan ke Redis PubSub, yang akan ditangkap oleh endpoint SSE
    await redis.publish(channel, message);

    console.log(`[EMIT] Memancarkan '${event}' ke '${channel}'`);

    return NextResponse.json({ success: true, message: "Signal transmitted" });
  } catch (error: unknown) {
    const msg = error instanceof Error ? error.message : "Unknown error";
    console.error("[EMIT] Gagal memancarkan sinyal:", msg);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
