import { Logger } from '@nestjs/common';
import {
  ConnectedSocket,
  MessageBody,
  OnGatewayConnection,
  OnGatewayDisconnect,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';

@WebSocketGateway({
  cors: {
    origin: '*',
  },
})
export class EventsGateway implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer()
  server: Server;

  private logger: Logger = new Logger('EventsGateway');

  handleConnection(client: Socket, ...args: any[]) {
    this.logger.log(`Client connected: ${client.id}`);
  }

  handleDisconnect(client: Socket) {
    this.logger.log(`Client disconnected: ${client.id}`);
  }

  @SubscribeMessage('join')
  handleJoin(
    @MessageBody() data: { room: string },
    @ConnectedSocket() client: Socket,
  ) {
    client.join(data.room);
    this.logger.log(`Client ${client.id} joined room: ${data.room}`);
    return { event: 'joined', data: { room: data.room } };
  }

  @SubscribeMessage('leave')
  handleLeave(
    @MessageBody() data: { room: string },
    @ConnectedSocket() client: Socket,
  ) {
    client.leave(data.room);
    this.logger.log(`Client ${client.id} left room: ${data.room}`);
    return { event: 'left', data: { room: data.room } };
  }

  // Broadcast methods for different events
  emitTaskUpdate(taskData: any) {
    this.server.emit('taskUpdate', taskData);
  }

  emitSettingsUpdate(settingsData: any) {
    this.server.emit('settingsUpdate', settingsData);
  }

  emitFileUpdate(fileData: any) {
    this.server.emit('fileUpdate', fileData);
  }

  emitMaintenanceUpdate(maintenanceData: any) {
    this.server.emit('maintenanceUpdate', maintenanceData);
  }

  emitWatcherUpdate(watcherData: any) {
    this.server.emit('watcherUpdate', watcherData);
  }

  emitToRoom(room: string, event: string, data: any) {
    this.server.to(room).emit(event, data);
  }
}
