import useDatabase from '~/composables/useDatabase';
import { projectFilesTable } from '~/db/schema';
import { hasPermissions } from '#shared/auth.util';

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 db = useDatabase();
    const content = db.select({ 
        path: projectFilesTable.path,
        owner: projectFilesTable.owner,
        title: projectFilesTable.title,
        type: projectFilesTable.type,
        navigable: projectFilesTable.navigable,
        private: projectFilesTable.private,
        order: projectFilesTable.order,
        timestamp: projectFilesTable.timestamp,
    }).from(projectFilesTable).all();

    content.sort((a, b) => {
        return a.path.split('/').length - b.path.split('/').length;
    });

    for(let i = 0; i < content.length; i++)
    {
        const path = content[i].path.substring(0, content[i].path.lastIndexOf('/'));
        if(path !== '')
        {
            const parent = content.find(e => e.path === path);

            if(parent)
            {
                content[i].private = content[i].private || parent.private;
            }
        }
    }

    return content.filter(e => e.type !== 'folder');
})