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

export default defineEventHandler(async (e) => {
    try
    {
        const id = getRouterParam(e, "id") ?? '';
        if(!id)
        {
            setResponseStatus(e, 404);
            return;
        }

        const db = useDatabase();
        const data = db.select({ content: sql<string>`cast(${content.content} as TEXT)`.as('content'), private: files.private, owner: files.owner, }).from(content).leftJoin(files, eq(content.id, files.id)).where(eq(content.id, id)).get();

        if(data && data.content)
        {
            const session = await getUserSession(e);

            if(!session || !session.user || session.user.id !== data.owner)
            {
                if(data.private)
                {
                    setResponseStatus(e, 404);
                    return;
                }
                else
                {
                    return data.content.replace(/%%(.+?)%%/g, "");
                }
            }

            return data.content;
        }
        
        setResponseStatus(e, 404);
        return;
    }
    catch(_e)
    {
        console.error(_e);
        setResponseStatus(e, 500);
        return;
    }
});