import { parentPort } from 'node:worker_threads'
import { QuestionDb } from '../../types/basicTypes'
import { getSubjectDifference } from '../../utils/qdbUtils'

export type MergeTaskObject = {
    type: 'merge'
    data: {
        localQdbIndex: number
        remoteQdb: QuestionDb
    }
}

export const handleMerge = async (
    qdbs: QuestionDb[],
    msg: MergeTaskObject,
    workerIndex: number
): Promise<void> => {
    const {
        localQdbIndex,
        remoteQdb,
    }: { localQdbIndex: number; remoteQdb: QuestionDb } = msg.data
    const localQdb = qdbs.find((qdb) => qdb.index === localQdbIndex)

    const { newData, newSubjects } = getSubjectDifference(
        localQdb.data,
        remoteQdb.data
    )

    parentPort.postMessage({
        msg: `From thread #${workerIndex}: merge done`,
        workerIndex: workerIndex,
        newData: newData,
        newSubjects: newSubjects,
        localQdbIndex: localQdbIndex,
    })
}
