// src/server/features/reference_books/lib/contractors.notifications.ts
// Notification utilities for contractors feature

import { db } from '@serverShared/db/client';
import { employees } from '@serverShared/db/schema';
import { eq } from 'drizzle-orm';
import { notifyUser } from '@serverShared/plugins/socket';

/**
 * Уведомить всех пользователей об изменении в списке контрагентов
 * Отправляет события напрямую через сокеты без создания записей в pending_notifications
 */
export async function notifyContractorsUpdate(event: string, data: Record<string, any>, tx?: any): Promise<void> {
  const client = tx || db;

  // Получаем всех НЕ УВОЛЕННЫХ пользователей (isFired = false)
  const employeesResult = await client
    .select({ id: employees.id })
    .from(employees)
    .where(eq(employees.isFired, false));

  const userIds = employeesResult.map((e: { id: string }) => e.id);

  // Отправляем события напрямую через сокеты без создания записей в pending_notifications
  if (userIds.length > 0) {
    await Promise.all(
      userIds.map((userId: string) =>
        notifyUser(userId, event as any, data)
      )
    );
  }
}
