import { createSubscriptionsClient } from '@gqty/subscriptions';
import type { SubscriptionsClient } from 'gqty';
import { hasuraQueryTypeHeader } from '../constants';
import type { Headers } from '../types';

// Create subscriptions client
export function createHasuraSubscriptionsClient(
  uri: string,
  getHeaders: (base?: Headers) => Promise<Headers>,
  enabled = true
): SubscriptionsClient | undefined {
  // Ensure we strictly check for false, not falsy values
  if (enabled === false) {
    // We must return undefined here, not a client when disabled
    return undefined;
  }

  try {
    const wsUrl = new URL(uri);
    wsUrl.protocol = wsUrl.protocol
      .replace('https', 'wss')
      .replace('http', 'ws');

    return createSubscriptionsClient({
      wsEndpoint: wsUrl.href,
      connectionInitPayload: async () => ({
        headers: await getHeaders({ [hasuraQueryTypeHeader]: 'subscription' }),
      }),
    });
  } catch (error) {
    console.error('Failed to create subscriptions client:', error);
    return undefined;
  }
}
