const { createClient, SubscribePayload } = require('graphql-ws');
const { WebSocket } = require('ws');

// const ws = new WebSocket('ws://localhost:8016/gqlapi', {
//   WebSocket,
// });

// const client = createClient({
//   url: 'ws://localhost:8016/gqlapi',
//   webSocketImpl: ws,
// });

// const ws = new WebSocket('ws://localhost:8016/gqlapi', {
//   headers: {
//     Authorization: "Basic YWRtaW46YWRtaW4="
//   }
// });

// const client = createClient({
//   url: 'ws://localhost:8016/gqlapi',
//   webSocketImpl: ws,
// });


const headers = {
    'Authorization': 'Basic YWRtaW46YWRtaW4=',
    'Content-Type': 'application/json',
    origin: 'abcdefg',
    // Other headers as needed
  };

// const ws = WebSocket('ws://localhost:8016/user-graphql-basic', {
//     headers: headers
// })

class MyWebSocket extends WebSocket {
    constructor(address, protocols) {
      super(address, protocols, {
        headers: headers
      });
    }
  }

const client = createClient({
url: 'ws://localhost:8016/gqlapi',
//url: 'wss://easyapi.ekika.app/user-graphql-apikey',
webSocketImpl: MyWebSocket,
});



const subscribeToSomething = async () => {
  const payload = {
    query: `
    subscription MySubscription{
        ResPartnerSub{
            name
            phone
            email
        }
    }
    `,
  };

  const onNext = (data) => {
    console.log('Received data:', data);
    // Send data to the client
    if (wsClient && wsClient.readyState === WebSocket.OPEN) {
      wsClient.send(JSON.stringify(data));
    }
  };

  const onError = (error) => {
    console.error('Subscription error:', error);
  };

  const onComplete = () => {
    console.log('Subscription complete');
  };

  await new Promise((resolve, reject) => {
    client.subscribe(payload, {
      next: onNext,
      error: onError,
      complete: onComplete,
    });
  });
};

// Keep track of the connected WebSocket client
let wsClient = null;

module.exports = { subscribeToSomething, setWsClient: (client) => { wsClient = client; } };
