import { parentPort } from 'node:worker_threads'
import { QuestionDb } from '../../types/basicTypes'
import { Edits, editDb } from '../../utils/actions'
import logger from '../../utils/logger'

export type DbEditTaskObject = {
    type: 'dbEdit'
    data: { dbIndex: number; edits: Edits }
}

export const handleDbEdit = async (
    qdbs: QuestionDb[],
    msg: DbEditTaskObject,
    workerIndex: number,
    setQdbs: (newVal: Array<QuestionDb>) => void
): Promise<void> => {
    const { dbIndex, edits }: { dbIndex: number; edits: Edits } = msg.data
    const { resultDb } = editDb(qdbs[dbIndex], edits)
    setQdbs(
        qdbs.map((qdb, i) => {
            if (i === dbIndex) {
                return resultDb
            } else {
                return qdb
            }
        })
    )
    logger.DebugLog(`Worker db edit ${workerIndex}`, 'worker update', 1)

    parentPort.postMessage({
        msg: `From thread #${workerIndex}: db edit`,
        workerIndex: workerIndex,
    })
}
