import { listWorkOrderShares } from '../../repositories/worker-platform/index.js'
import {
  publishWorkerWalletRealtimeChange,
  publishWorkOrderRealtimeChange,
} from '../realtime/realtime-event-service.js'

/** 拼单工单同步所有参与打手，避免仅主打手页面更新。 */
export async function publishWorkOrderParticipantChange(
  workOrderId: number,
  options: {
    workerIds?: number[]
    hallChanged?: boolean
    walletChangedWorkerIds?: number[]
  } = {},
) {
  const shares = await listWorkOrderShares(workOrderId)
  const workerIds = [
    ...(options.workerIds || []),
    ...shares.map((share) => Number(share.worker_id)),
  ].filter(
    (workerId, index, values) =>
      Number.isInteger(workerId) && workerId > 0 && values.indexOf(workerId) === index,
  )
  publishWorkOrderRealtimeChange({
    workOrderId,
    workerIds,
    ...(options.hallChanged ? { hallChanged: true } : {}),
  })
  for (const workerId of options.walletChangedWorkerIds || []) {
    publishWorkerWalletRealtimeChange(workerId)
  }
}
