import {retrieveFromDatabase} from './NIET_OPENEN_WORDT_GEBRUIKT_DOOR_DE_API_FILES/databaseSimulation.ts'
import {USER_KEY} from './NIET_OPENEN_WORDT_GEBRUIKT_DOOR_DE_API_FILES/generateData.ts'
import {useMutation, UseMutationResult, useQuery, useQueryClient, UseQueryResult} from '@tanstack/react-query'
import {IUser} from '../models/IUser.ts'

//region Mutations & queries

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


export const useGetUser = (): UseQueryResult<IUser, Error> => {
    return useQuery({
        queryKey: ['user'],
        queryFn: getUser,
    })
}

export const useLogin = (): UseMutationResult<IUser, Error, void, void> => {
    const queryClient = useQueryClient()
    return useMutation({
        mutationFn: login,
        onSuccess: (data) => {
            queryClient.setQueryData<IUser>(['user'], data)
        }
    })
}

export const useLogout = (): UseMutationResult<void, Error, void, void> => {
    const queryClient = useQueryClient()
    return useMutation({
        mutationFn: logout,
        onSuccess: () => {
            queryClient.setQueryData<IUser | null>(['user'], null)
        }
    })
}

//endregion


//region API functions


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

/**
 * Login
 */
async function login(): Promise<IUser> {
    localStorage.setItem(USER_KEY, 'true')
    return {name: 'Admin'}
}

async function logout(): Promise<void> {
    localStorage.removeItem(USER_KEY)
    return
}

/**
 * Retrieve the user, returns null when not logged in.
 */
async function getUser(): Promise<IUser | null> {
    const loggedIn = await retrieveFromDatabase<boolean>(USER_KEY)

    if (loggedIn) {
        return {name: 'Admin'}
    } else return null
}

//endregion
