import { hasPermissions } from "#shared/auth.util";

declare module 'nitropack'
{
    interface TaskPayload
    {
        type: string;
    }
    interface TaskResult<RT = unknown>
    {
        error?: Error | string;
    }
}

export default defineEventHandler(async (e) => {
    const session = await getUserSession(e);

    if(!session.user || !hasPermissions(session.user.permissions, ['admin']))
    {
        setResponseStatus(e, 404);
        return;
    }
    const id = getRouterParam(e, 'id');
    const body: Record<string, any> = await readBody(e);

    if(!id)
    {
        setResponseStatus(e, 400);
        return;
    }

    body.data = JSON.parse(body.data);
    const payload = {
        type: id,
        data: body,
    }
    
    const result = await runTask(id, {
        payload: payload
    });

    if(!result.result)
    {
        setResponseStatus(e, 500);

        if(result.error && result.error.message)
            throw result.error;
        else if(result.error)
            throw new Error(result.error);
        else
            throw new Error('Erreur inconnue');
    }
    return;
});