import {
    persistToDatabase,
    retrieveFromDatabase,
} from './NIET_OPENEN_WORDT_GEBRUIKT_DOOR_DE_API_FILES/databaseSimulation.ts'
import {ITriviaQuestion} from '../models/ITriviaQuestion.ts'
import {TRIVIA_KEY} from './NIET_OPENEN_WORDT_GEBRUIKT_DOOR_DE_API_FILES/generateData.ts'

//region Mutations & queries

/**
 * ---------------------------------------------------------------------------------------------------------------------
 *                                          MUTATIONS & QUERIES
 * ---------------------------------------------------------------------------------------------------------------------
 */


//endregion


//region API functions

/**
 * ---------------------------------------------------------------------------------------------------------------------
 *                                          API functions
 * ---------------------------------------------------------------------------------------------------------------------
 */

/**
 * Haal alle trivia vragen op.
 */
async function getAllTriviaQuestions(): Promise<ITriviaQuestion[]> {
    return  retrieveFromDatabase<ITriviaQuestion[]>(TRIVIA_KEY)
}

/**
 * Haal een specifieke trivia vraag op.
 *
 * @param id Het id van de vraag die opgehaald moet worden.
 */
async function getTriviaQuestion(id: string): Promise<ITriviaQuestion | undefined> {
    const questions = await retrieveFromDatabase<ITriviaQuestion[]>(TRIVIA_KEY)
    return questions.find(x => x.id === id)
}

interface UpdateTriviaQuestionParams {
    question: ITriviaQuestion
}

/**
 * Pas de eigenschappen van een trivia vraag aan.
 *
 * @param question De nieuwe eigenschappen van de Trivia Vraag.
 */
async function updateTriviaQuestion({question}: UpdateTriviaQuestionParams): Promise<ITriviaQuestion> {
    const questions = await retrieveFromDatabase<ITriviaQuestion[]>(TRIVIA_KEY)
    const index = questions.findIndex(x => x.id === question.id)
    questions[index] = question

    await persistToDatabase(TRIVIA_KEY, questions)
    return window.structuredClone(question)
}

interface DeleteTriviaQuestionParams {
    id: string
}

/**
 * Verwijder een trivia vraag.
 *
 * @param id Het is van de vraag die verwijderd moet worden.
 */
async function deleteTriviaQuestion({id}: DeleteTriviaQuestionParams): Promise<void> {
    const questions = await retrieveFromDatabase<ITriviaQuestion[]>(TRIVIA_KEY)
    const index = questions.findIndex(x => x.id === id)
    questions.splice(index, 1)

    await persistToDatabase(TRIVIA_KEY, questions)
}

//endregion
