import { createClient } from "@/lib/supabase/server";

/**
 * Gets or creates a conversation between two users
 * Uses the database RPC function 'get_or_create_conversation' to handle
 * the logic of finding existing conversations or creating new ones
 * 
 * @param user1Id - ID of the first user in the conversation
 * @param user2Id - ID of the second user in the conversation
 * @returns Promise resolving to the conversation ID
 * @throws Error if the database operation fails
 * 
 * @example
 * const conversationId = await getOrCreateConversation('user-123', 'user-456');
 */
export async function getOrCreateConversation(user1Id: string, user2Id: string) {
  const supabase = await createClient();

  // Use the database function to get or create conversation
  const { data: conversationId, error } = await supabase
    .rpc('get_or_create_conversation', {
      user1_id: user1Id,
      user2_id: user2Id
    });

  if (error) {
    throw new Error(`Failed to get or create conversation: ${error.message}`);
  }

  return conversationId as string;
}