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

export type NewQuestionTaskObject = {
    type: 'newQuestions'
    data: Omit<Result, 'qdbName'>
}

export const handleNewQuestions = async (
    qdbs: QuestionDb[],
    msg: NewQuestionTaskObject,
    workerIndex: number,
    setQdbs: (newVal: Array<QuestionDb>) => void
): Promise<void> => {
    const { subjName, qdbIndex, newQuestions } = msg.data

    const newQuestionsWithCache = newQuestions.map((question) => {
        if (!question.cache) {
            return createQuestion(question)
        } else {
            return question
        }
    })

    let added = false
    setQdbs(
        qdbs.map((qdb) => {
            if (qdb.index === qdbIndex) {
                return {
                    ...qdb,
                    data: qdb.data.map((subj) => {
                        if (subj.Name === subjName) {
                            added = true
                            return {
                                Name: subj.Name,
                                Questions: [
                                    ...subj.Questions,
                                    ...newQuestionsWithCache,
                                ],
                            }
                        } else {
                            return subj
                        }
                    }),
                }
            } else {
                return qdb
            }
        })
    )

    if (!added) {
        setQdbs(
            qdbs.map((qdb) => {
                if (qdb.index === qdbIndex) {
                    return {
                        ...qdb,
                        data: [
                            ...qdb.data,
                            {
                                Name: subjName,
                                Questions: [...newQuestionsWithCache],
                            },
                        ],
                    }
                } else {
                    return qdb
                }
            })
        )
    }

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