import { Server as HTTPServer } from 'http';
import { Server as SocketIOServer, Socket } from 'socket.io';

let io: SocketIOServer | null = null;

export function initializeWebSocket(httpServer: HTTPServer): SocketIOServer {
  io = new SocketIOServer(httpServer, {
    cors: {
      origin: process.env.NODE_ENV === 'production' 
        ? process.env.REPLIT_DOMAINS?.split(',') || []
        : ['http://localhost:5000', 'http://0.0.0.0:5000'],
      credentials: true,
    },
    transports: ['websocket', 'polling'],
  });

  io.on('connection', (socket: Socket) => {
    console.log(`✅ Client connected: ${socket.id}`);

    socket.on('join:match', (matchId: number) => {
      socket.join(`match:${matchId}`);
      console.log(`Client ${socket.id} joined match ${matchId}`);
    });

    socket.on('leave:match', (matchId: number) => {
      socket.leave(`match:${matchId}`);
      console.log(`Client ${socket.id} left match ${matchId}`);
    });

    socket.on('join:team', (teamId: number) => {
      socket.join(`team:${teamId}`);
      console.log(`Client ${socket.id} joined team ${teamId}`);
    });

    socket.on('leave:team', (teamId: number) => {
      socket.leave(`team:${teamId}`);
      console.log(`Client ${socket.id} left team ${teamId}`);
    });

    socket.on('disconnect', () => {
      console.log(`Client disconnected: ${socket.id}`);
    });
  });

  console.log('✅ WebSocket server initialized');
  return io;
}

export function getIO(): SocketIOServer {
  if (!io) {
    throw new Error('WebSocket server not initialized. Call initializeWebSocket first.');
  }
  return io;
}

export interface MatchEvent {
  matchId: number;
  type: 'goal' | 'card' | 'substitution' | 'halftime' | 'fulltime' | 'status_change';
  timestamp: Date;
  data: any;
}

export interface TeamNotification {
  teamId: number;
  type: 'announcement' | 'training' | 'match_reminder' | 'player_update';
  title: string;
  message: string;
  timestamp: Date;
}

export function emitMatchEvent(event: MatchEvent): void {
  const socketIO = getIO();
  socketIO.to(`match:${event.matchId}`).emit('match:event', event);
  console.log(`Emitted match event for match ${event.matchId}: ${event.type}`);
}

export function emitTeamNotification(notification: TeamNotification): void {
  const socketIO = getIO();
  socketIO.to(`team:${notification.teamId}`).emit('team:notification', notification);
  console.log(`Emitted team notification for team ${notification.teamId}: ${notification.type}`);
}

export function emitToUser(userId: number, event: string, data: any): void {
  const socketIO = getIO();
  socketIO.to(`user:${userId}`).emit(event, data);
}

export function broadcastGlobal(event: string, data: any): void {
  const socketIO = getIO();
  socketIO.emit(event, data);
}
