import { eq, sql } from 'drizzle-orm';
import useDatabase from '~/composables/useDatabase';
import { projectFilesTable } from '~/db/schema';

export default defineCachedEventHandler(async (e) => {
    const id = getRouterParam(e, "id") ?? '';

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

    const db = useDatabase();

    const content = db.select({ 
        'id': projectFilesTable.id,
        'path': projectFilesTable.path,
        'owner': projectFilesTable.owner,
        'title': projectFilesTable.title,
        'type': projectFilesTable.type,
        'navigable': projectFilesTable.navigable,
        'private': projectFilesTable.private,
    }).from(projectFilesTable).where(eq(projectFilesTable.id, sql.placeholder('id'))).prepare().get({ id });

    if(content !== undefined)
    {
        const session = await getUserSession(e);

        if(content.private && (!session || !session.user))
        {
            setResponseStatus(e, 404);
            return;
        }
        if(session && session.user && content.private && session.user.id !== content.owner)
        {
            setResponseStatus(e, 404);
            return;
        }
        
        return { 
            path: content.path,
            owner: content.owner,
            title: content.title,
            type: content.type,
        };
    }
    
    setResponseStatus(e, 404);
    return;
}, { getKey: (e) => getRouterParam(e, "id") ?? '', });