import { desc, sql } from 'drizzle-orm' export default defineEventHandler(() => { const db = useDb() const rows = db.select().from(tables.projects).orderBy(desc(tables.projects.updatedAt)).all() const stats = db.select({ projectId: tables.chapters.projectId, total: sql`count(*)`, approved: sql`sum(case when ${tables.chapters.status} = 'approved' then 1 else 0 end)`, words: sql`coalesce(sum((select word_count from chapter_versions v where v.id = ${tables.chapters.activeVersionId})), 0)` }).from(tables.chapters).groupBy(tables.chapters.projectId).all() return rows.map(p => ({ id: p.id, title: p.title, description: p.description, updatedAt: p.updatedAt, stats: stats.find(s => s.projectId === p.id) ?? { total: 0, approved: 0, words: 0 }, running: getActiveRun(p.id) })) })