import { hasPermissions } from "~/shared/auth.util";
import useDatabase from '~/composables/useDatabase';
import { and, eq, notInArray } from "drizzle-orm";
import { z } from "zod";
import { userPermissionsTable } from "~/db/schema";

const schema = z.array(z.string());

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

    if(!session || !session.user || !hasPermissions(session.user.permissions, ['admin']))
    {
        throw createError({
            statusCode: 401,
            message: 'Unauthorized',
        });
    }

    const param = getRouterParam(e, 'id');

    if(!param)
    {
        throw createError({
            statusCode: 403,
            message: 'Forbidden',
        });
    }

    const body = await readValidatedBody(e, schema.safeParse);

    if(!body.success)
    {
        throw createError({
            statusCode: 403,
            message: 'Forbidden',
        });
    }

    try {
        const id = parseInt(param, 10);

        const db = useDatabase();
        const permissions = body.data.map(e => ({ id: id, permission: e }));

        db.transaction((tx) => {
            tx.delete(userPermissionsTable).where(eq(userPermissionsTable.id, id)).run();
            tx.insert(userPermissionsTable).values(permissions).run();
        });
    } catch(e) {
        console.error(e);

        throw e;
    }
});