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

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

    if(!user || !hasPermissions(user.permissions, ['admin', 'editor']))
    {
        throw createError({ statusCode: 401, statusText: 'Unauthorized' });
    }
    
    try
    {
        const id = getRouterParam(e, "id") ?? '';
        const body = await readRawBody(e);
        
        if(!id)
        {
            setResponseStatus(e, 404);
            return;
        }

        const db = useDatabase();
        const item = db.select({ id: projectFilesTable.id }).from(projectFilesTable).where(eq(projectFilesTable.id, id)).get();

        if(!item)
        {
            setResponseStatus(e, 404);
            return;
        }

        db.insert(projectContentTable).values({ id: id, content: body }).onConflictDoUpdate({ set: { content: body }, target: projectContentTable.id }).run();
        db.update(projectFilesTable).set({ timestamp: new Date() }).where(eq(projectFilesTable.id, id)).run()
    }
    catch(_e)
    {
        console.error(_e);
        setResponseStatus(e, 500);
        return;
    }
});