import { Injectable, inject } from '@angular/core';
import { Store } from '@ngrx/store';
import type { User } from '../../../../shared-kernel';
import { VoiceConnectionFacade } from '../../../voice-connection';
import { ClientInstanceService } from '../../../../core/platform/client-instance.service';
import { UsersActions } from '../../../../store/users/users.actions';
import { isLocalVoiceOwner } from '../../domain/logic/client-voice-session.rules';
import { VoiceSessionFacade } from '../facades/voice-session.facade';

@Injectable({ providedIn: 'root' })
export class VoiceClientTakeoverService {
  private readonly store = inject(Store);
  private readonly voiceConnection = inject(VoiceConnectionFacade);
  private readonly voiceSession = inject(VoiceSessionFacade);
  private readonly clientInstance = inject(ClientInstanceService);

  releaseLocalVoiceForTakeover(currentUser: User | null): void {
    if (!currentUser?.voiceState?.isConnected) {
      return;
    }

    if (!isLocalVoiceOwner(currentUser.voiceState, this.clientInstance.getClientInstanceId())) {
      return;
    }

    const previousVoiceState = currentUser.voiceState;

    this.voiceConnection.stopVoiceHeartbeat();
    this.voiceConnection.disableVoice();

    this.store.dispatch(
      UsersActions.updateVoiceState({
        userId: currentUser.id,
        voiceState: {
          isConnected: false,
          isMuted: false,
          isDeafened: false,
          roomId: undefined,
          serverId: undefined,
          clientInstanceId: undefined
        }
      })
    );

    this.store.dispatch(
      UsersActions.updateCameraState({
        userId: currentUser.id,
        cameraState: { isEnabled: false }
      })
    );

    this.voiceConnection.broadcastMessage({
      type: 'voice-state',
      oderId: currentUser.oderId || currentUser.id,
      displayName: currentUser.displayName || 'User',
      voiceState: {
        isConnected: false,
        isMuted: false,
        isDeafened: false,
        roomId: previousVoiceState.roomId,
        serverId: previousVoiceState.serverId,
        clientInstanceId: undefined
      }
    });

    this.voiceSession.endSession();
  }
}
