import { Server as SocketIOServer } from 'socket.io';
import { Server as HTTPServer } from 'http';
import { auth } from '@/auth';

let io: SocketIOServer | null = null;

export function initSocket(server: HTTPServer) {
  io = new SocketIOServer(server, {
    cors: {
      origin: process.env.NEXTAUTH_URL || "http://localhost:3000",
      methods: ["GET", "POST"],
    },
  });

  io.on('connection', async (socket) => {
    console.log('User connected:', socket.id);

    // Authenticate user and join their rooms
    socket.on('authenticate', async (sessionToken) => {
      try {
        const session = await auth();
        if (session?.user?.email) {
          // Join user-specific room
          socket.join(`user:${session.user.email}`);
          console.log(`User ${session.user.email} authenticated and joined room`);
        }
      } catch (error) {
        console.error('Socket authentication error:', error);
      }
    });

    // Join workspace room
    socket.on('join-workspace', (workspaceId) => {
      socket.join(`workspace:${workspaceId}`);
      console.log(`User joined workspace room: ${workspaceId}`);
    });

    // Leave workspace room
    socket.on('leave-workspace', (workspaceId) => {
      socket.leave(`workspace:${workspaceId}`);
      console.log(`User left workspace room: ${workspaceId}`);
    });

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

  return io;
}

export function getSocket() {
  return io;
}

export async function emitNotification(userId: string, notification: any) {
  if (!io) return;
  
  console.log('Emitting notification to user ID:', userId);
  console.log('Notification:', notification);
  
  // Get user email for socket room
  try {
    const { prisma } = await import('@/lib/prisma');
    const user = await prisma.user.findUnique({
      where: { id: userId },
      select: { email: true }
    });
    
    if (user?.email) {
      console.log('Emitting to user email:', user.email);
      io.to(`user:${user.email}`).emit('notification', notification);
    } else {
      console.log('User not found for ID:', userId);
    }
  } catch (error) {
    console.error('Error getting user email for notification:', error);
  }
}

export function emitToWorkspace(workspaceId: string, event: string, data: any) {
  if (!io) return;
  
  io.to(`workspace:${workspaceId}`).emit(event, data);
} 