import type { Server as IOServer } from "socket.io";
import type { z } from "zod";
import { channelRoom } from "./channel-room";
import type { IRealtimeBroadcaster } from "./realtime-broadcaster.interface";
import type { RealtimeChannelDescriptor } from "./realtime-channel";

export class SocketIORealtimeBroadcaster implements IRealtimeBroadcaster {
  constructor(private readonly io: IOServer) {}

  async broadcast<T>(
    descriptor: RealtimeChannelDescriptor<string, z.ZodType<T>>,
    payload: T,
  ): Promise<void> {
    descriptor.schema.parse(payload);
    this.io.to(channelRoom(descriptor.name)).emit(descriptor.name, payload);
  }
}
