import * as signalR from '@microsoft/signalr'

let connection: signalR.HubConnection | null = null

export const connectToHub = async (): Promise<string> => {
  console.log('Connecting to SignalR Hub...')

  // Mevcut bağlantı varsa her durumda kapat (Connected, Reconnecting, Disconnected)
  if (connection) {
    try {
      await connection.stop()
    } catch {
      // Bağlantı zaten kapalı olabilir, yoksay
    }
    connection = null
  }

  connection = new signalR.HubConnectionBuilder()
    .withUrl(import.meta.env.VITE_SOCKET_URL, {
      withCredentials: false,
      skipNegotiation: true,
      transport: signalR.HttpTransportType.WebSockets
    })
    .withAutomaticReconnect()
    .build()

  // Eventleri ekle (connection artık tanımlı)
  connection.on('ReceiveProgress', (data: any) => console.log('progress', data))
  connection.on('ReceiveInsertProgress', (data: any) => console.log('insert progress', data))
  connection.on('ReceiveCompleted', (data: any) => console.log('completed', data))
  connection.on('ReceiveError', (data: any) => console.log('error', data))

  try {
    await connection.start()
    const connectionId = await connection.invoke<string>('GetConnectionId')
    console.log('Connected to SignalR Hub with Connection ID:', connectionId)
    return connectionId
  } catch (err) {
    connection = null
    throw err
  }
}

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

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

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

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

/** Upload event handler'larını kaldır (memory leak ve çoklu tetikleme önleme) */
export const removeUploadHandlers = () => {
  if (connection) {
    connection.off('ReceiveProgress')
    connection.off('ReceiveInsertProgress')
    connection.off('ReceiveCompleted')
    connection.off('ReceiveError')
  }
}
