import { parentPort } from 'node:worker_threads'
import { PeerInfo, QuestionDb } from '../../types/basicTypes'
import { files, readAndValidateFile } from '../../utils/files'
import { post } from '../../utils/networkUtils'
import {
    loginAndPostDataToAllPeers,
    peerToString,
} from '../../modules/api/p2p/p2putils'
import { NewUserFilesRequestBody } from '../../modules/api/p2p/userFiles'
import { UserDirDataFile } from '../../modules/api/submodules/userFiles'

export type UserFilesToPeersTaskObject = {
    type: 'sendUserFilesToPeers'
    data: {
        dir: string
        fileName: string
        fileData: UserDirDataFile
    }
}

export const handleUserFilesToPeers = async (
    _qdbs: QuestionDb[],
    msg: UserFilesToPeersTaskObject,
    workerIndex: number
): Promise<void> => {
    const { dir, fileName, fileData } = msg.data

    const selfInfo = readAndValidateFile<PeerInfo>(files.selfInfoFile)
    const host = peerToString(selfInfo)
    const peers = readAndValidateFile<PeerInfo[]>(files.peersFile)

    if (!peers || peers.length === 0) {
        parentPort.postMessage({
            msg: `From thread #${workerIndex}: sendUserFilesToPeers done`,
            workerIndex: workerIndex,
        })
        return
    }

    const dataToSend: NewUserFilesRequestBody = {
        host: host,
        newFiles: {
            [dir]: { [fileName]: fileData },
        },
    }

    const postData = (peer: PeerInfo, sessionCookie: string) => {
        return post({
            hostname: peer.host,
            port: peer.port,
            http: peer.http,
            path: '/api/newuserfilecreated',
            bodyObject: dataToSend,
            cookie: `sessionID=${sessionCookie}`,
        })
    }

    loginAndPostDataToAllPeers(peers, postData)

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