/*
 * Copyright (c) 2022.
 * Author Peter Placzek (tada5hi)
 * For the full copyright and license information,
 * view the LICENSE file that was distributed with this source code.
 */

import {lazy, number, object, ObjectSchema, string} from "yup";

export interface SocketEventMessage {
    type?: string,
    id?: number | string,
    data?: any,
    meta?: {[key: string] : any}
}

let validatorInstance : undefined | ObjectSchema;

export function useSocketEventMessageValidator() : ObjectSchema {
    if(typeof validatorInstance !== 'undefined') {
        return validatorInstance;
    }

    validatorInstance = object({
        type: string().optional().min(3),
        id: lazy(value => typeof value === 'string' ? string().optional() : number().optional()),
        data: object().optional().noUnknown(false).default({}),
        meta: object().optional().noUnknown(false).default( {})
    }).optional().noUnknown().default(undefined);

    return validatorInstance;
}

export async function parseSocketEventMessage(value: unknown) : Promise<SocketEventMessage> {
    return await useSocketEventMessageValidator().validate(value);
}
