import useDatabase from '~/composables/useDatabase';
import { projectFilesTable } from '~/db/schema';

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

    const db = useDatabase();
    const content = db.select().from(projectFilesTable).all();

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

    if(content.length > 0)
    {
        for(const idx in content)
        {
            const item = content[idx];
            if(!!item.private && (user?.id ?? -1) !== item.owner)
            {
                delete content[idx];
                continue;
            }
            
            const parent = item.path.includes('/') ? item.path.substring(0, item.path.lastIndexOf('/')) : undefined;

            if(parent && !content.find(e => e && e.path === parent))
            {
                delete content[idx];
                continue;
            }
        }

        return content.filter(e => !!e);
    }
    
    return [];
});