import { supabase } from '@/integrations/supabase/client';
import type { RealtimeChannel } from '@supabase/supabase-js';

export type SignalMessage =
  | { type: 'viewer-join'; viewerId: string }
  | { type: 'viewer-leave'; viewerId: string }
  | { type: 'offer'; viewerId: string; sdp: RTCSessionDescriptionInit }
  | { type: 'answer'; viewerId: string; sdp: RTCSessionDescriptionInit }
  | { type: 'ice'; viewerId: string; from: 'broadcaster' | 'viewer'; candidate: RTCIceCandidateInit };

export function joinSignalingChannel(
  code: string,
  onMessage: (msg: SignalMessage) => void,
): RealtimeChannel {
  const channel = supabase.channel(`share:${code}`, {
    config: { broadcast: { self: false, ack: false } },
  });

  channel
    .on('broadcast', { event: 'signal' }, ({ payload }) => onMessage(payload as SignalMessage))
    .subscribe();

  return channel;
}

export function sendSignal(channel: RealtimeChannel, msg: SignalMessage) {
  return channel.send({ type: 'broadcast', event: 'signal', payload: msg });
}

export function generateRoomCode(): string {
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // unambiguous
  let out = '';
  for (let i = 0; i < 6; i++) out += chars[Math.floor(Math.random() * chars.length)];
  return out;
}

export const ICE_SERVERS: RTCIceServer[] = [
  { urls: 'stun:stun.l.google.com:19302' },
  { urls: 'stun:stun1.l.google.com:19302' },
];
