import { Injectable, inject } from '@angular/core'
import { NotificationEventType } from '@core/types'
import { Socket } from 'ngx-socket-io'
import { map } from 'rxjs'

const CHANNEL = 'events'
type Message = { event: NotificationEventType; userId: string }

@Injectable()
export class WSService {
	private readonly _socket = inject(Socket)

	readonly messages$ = this._socket.fromEvent<Message, string>(CHANNEL).pipe(map((data) => data))

	connect(tenantId: string, userId: string): void {
		this._socket.emit(CHANNEL, { tenantId, userId })

		// On every reconnect, send this event to create a new subscription
		this._socket.on('connect', () => {
			this._socket.emit(CHANNEL, { tenantId, userId })
		})
	}

	disconnect(): void {
		this._socket.disconnect()
	}
}
