import { getCurrentUser } from "../user"; import { Block, PageMeta, PageStatus, PageType } from "./types"; import { prisma } from "../prisma"; export async function getPages(type: PageType, status: PageStatus, limit?: number) { return await prisma.page.findMany({ where: { type, status }, take: limit, orderBy: { publishedAt: "desc" }, }); } export async function getPageById(id: string) { return await prisma.page.findUnique({ where: { id: id } }); } export async function getPageBySlug(slug: string) { return await prisma.page.findUnique({ where: { slug } }); } export async function createPage(slug: string, title: string, type: PageType, status: PageStatus, blocks: Block[], meta?: PageMeta) { const user = await getCurrentUser(); if (!user) { throw new Error("Failed to fetch user"); } if (!user.isAdmin) { throw new Error("Access denied") } const existingPage = await prisma.page.findUnique({ where: { slug } }); if (existingPage) { throw new Error("Page already exists"); } const page = await prisma.page.create({ data: { slug, title, type, status, meta: meta ?? {}, publishedAt: status === "PUBLISHED" ? new Date() : null, createdBy: user.id }, }); if (blocks.length > 0) { await prisma.block.createMany({ data: blocks.map((block) => ({ pageId: page.id, parentId: block.parentId, type: block.type, position: block.position, content: block.content, })), }); } return page; } export async function updatePage( id: string, title: string, type: PageType, status: PageStatus, blocks: Block[], meta?: PageMeta ) { const user = await getCurrentUser(); if (!user?.isAdmin) throw new Error("Access denied"); const page = await prisma.page.update({ where: { id }, data: { title, type, status, meta: meta ?? {}, publishedAt: status === "PUBLISHED" ? new Date() : undefined, updatedAt: new Date(), updatedBy: user.id }, }); await prisma.$transaction([ prisma.block.deleteMany({ where: { pageId: id } }), ...(blocks.length > 0 ? [prisma.block.createMany({ data: blocks.map((b) => ({ pageId: id, parentId: b.parentId, type: b.type, position: b.position, content: b.content as any, })), })] : []), ]); return page; } export async function archivePage(id: string) { const user = await getCurrentUser(); if (!user?.isAdmin) throw new Error("Access denied"); await prisma.page.update({ where: { id }, data: { status: "ARCHIVED", updatedBy: user.id } }); } export async function deletePage(id: string) { const user = await getCurrentUser(); if (!user?.isAdmin) throw new Error("Access denied"); await prisma.page.delete({ where: { id } }); } export async function getBlocksByPageId(pageId: string) { return prisma.block.findMany({ where: { pageId }, orderBy: { position: "asc" }, }); }