import type { AppSupabaseClient } from '../supabase/client.js';
import type { LivekitToken } from './types.js';

// Fetch a short-lived LiveKit access token via the mint-livekit-token
// edge function. The server-side RLS check lives inside that function.
export async function fetchLivekitToken(
  client: AppSupabaseClient,
  conversationId: string,
): Promise<LivekitToken> {
  const { data, error } = await client.functions.invoke('mint-livekit-token', {
    body: { conversationId },
  });
  if (error) throw error;
  if (!data || typeof data !== 'object') {
    throw new Error('invalid token response');
  }
  const d = data as Partial<LivekitToken>;
  if (!d.token || !d.url || !d.roomName || !d.identity) {
    throw new Error('incomplete token response');
  }
  return {
    token: d.token,
    url: d.url,
    roomName: d.roomName,
    identity: d.identity,
  };
}
