import { NextRequest, NextResponse } from "next/server";
import Redis from "ioredis";

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

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 });
    }

    // IAM tidak menangani host_approve_guest secara langsung dengan DB pg

    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) {
    const message = error instanceof Error ? error.message : "Gagal memancarkan sinyal";
    console.error("[EMIT] Gagal memancarkan sinyal:", message);
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
