import useDatabase from '~/composables/useDatabase';
import { hasPermissions } from "#shared/auth.util";
import { eq, sql } from "drizzle-orm";
import { projectFilesTable } from "~/db/schema";
import { Project } from "~/schemas/project";

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

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

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

    if(!body.success)
    {
        throw body.error;
    }

    const db = useDatabase(), items = body.data, blocked: string[] = [];

    db.transaction((tx) => {
        const data = tx.select({ id: projectFilesTable.id, timestamp: projectFilesTable.timestamp }).from(projectFilesTable).all();
        const deletion = tx.delete(projectFilesTable).where(eq(projectFilesTable.id, sql.placeholder('id'))).prepare();

        for(let i = 0; i < items.length; i++)
        {
            const item = items[i];

            const index = data.findIndex(e => e.id === item.id);

            if(index !== -1)
            {
                if(data[index].timestamp > new Date(item.timestamp))
                {
                    blocked.push(item.id);
                    continue;
                }

                data.splice(index, 1);
            }

            tx.insert(projectFilesTable).values({
                id: item.id,
                path: item.path,
                owner: user.id,
                title: item.title,
                type: item.type,
                navigable: item.navigable,
                private: item.private,
                order: item.order,
            }).onConflictDoUpdate({
                set: {
                    id: item.id,
                    path: item.path,
                    title: item.title,
                    type: item.type,
                    navigable: item.navigable,
                    private: item.private,
                    order: item.order,
                    timestamp: new Date(),
                },
                target: projectFilesTable.id,
            }).run();
        }

        for(let i = 0; i < data.length; i++)
        {
            deletion.run({ id: data[i].id });
        }
    });

    return blocked;
});