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

declare module 'nitropack'
{
    interface TaskPayload
    {
        type: 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 payload: Record<string, any> = await readBody(e);

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

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

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

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