import {
  WebSocketGateway,
  WebSocketServer,
  SubscribeMessage,
  OnGatewayConnection,
  OnGatewayDisconnect,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { OnEvent } from '@nestjs/event-emitter';
import { Logger } from '@nestjs/common';

@WebSocketGateway({ cors: { origin: '*' }, namespace: '/notifications' })
export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer() server: Server;
  private readonly logger = new Logger(NotificationsGateway.name);
  private clients = new Map<string, string>(); // socketId -> tenantId

  handleConnection(client: Socket) {
    const tenantId = client.handshake.query.tenantId as string;
    if (tenantId) {
      this.clients.set(client.id, tenantId);
      client.join(`tenant:${tenantId}`);
      this.logger.log(`Client connected: ${client.id} | Tenant: ${tenantId}`);
    }
  }

  handleDisconnect(client: Socket) {
    this.clients.delete(client.id);
  }

  @OnEvent('notification.created')
  handleNotification(payload: { tenantId: string }) {
    this.server.to(`tenant:${payload.tenantId}`).emit('notification', { refresh: true });
  }

  @OnEvent('order.completed')
  handleOrderCompleted(payload: { tenantId: string; orderId: string }) {
    this.server.to(`tenant:${payload.tenantId}`).emit('order:completed', { orderId: payload.orderId });
  }
}
