import * as signalR from "@microsoft/signalr";
import { v4 as uuidv4 } from "uuid";

let connection: signalR.HubConnection;
let connectionId = "";

export const connectToHub = async () => {
  connection = new signalR.HubConnectionBuilder()
    .withUrl("https://panelapi.cekilisevi.gov.tr/uploadHub", {
      withCredentials: false  // Bu zorunlu, yoksa cookie vs gönderilmez
    }) // backend adresine göre düzenle
    .withAutomaticReconnect()
    .build();

  await connection.start();
  connectionId = connection.connectionId || uuidv4(); // SignalR id'si ya da frontend'de de guid üretilebilir
  return connectionId;
};

export const onProgress = (callback: (data: any) => void) => {
  connection.on("ReceiveProgress", callback);
};

export const onInsertProgress = (callback: (data: any) => void) => {
  connection.on("ReceiveInsertProgress", callback);
};

export const onCompleted = (callback: (data: any) => void) => {
  connection.on("ReceiveCompleted", callback);
};

export const onError = (callback: (data: any) => void) => {
  connection.on("ReceiveError", callback);
};