import { Injectable, NotFoundException } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; import { CreateCmsContentDto, UpdateCmsContentDto } from './dto'; import { AuditService } from '../audit/audit.service'; import { AuditAction } from '../audit/audit.constants'; @Injectable() export class CmsService { constructor( private prisma: PrismaService, private audit: AuditService, ) {} async findByPage(pageSlug: string) { return this.prisma.cmsContent.findMany({ where: { pageSlug, isPublished: true }, orderBy: { sectionKey: 'asc' }, }); } async findByPageAndSection(pageSlug: string, sectionKey: string) { const content = await this.prisma.cmsContent.findUnique({ where: { pageSlug_sectionKey: { pageSlug, sectionKey } }, }); if (!content) { throw new NotFoundException(`CMS content not found for ${pageSlug}/${sectionKey}`); } return content; } async upsert(dto: CreateCmsContentDto) { return this.prisma.cmsContent.upsert({ where: { pageSlug_sectionKey: { pageSlug: dto.pageSlug, sectionKey: dto.sectionKey, }, }, update: { content: dto.content, isPublished: dto.isPublished ?? true, }, create: { pageSlug: dto.pageSlug, sectionKey: dto.sectionKey, content: dto.content, isPublished: dto.isPublished ?? true, }, }); } async update(id: string, dto: UpdateCmsContentDto) { const existing = await this.prisma.cmsContent.findUnique({ where: { id } }); if (!existing) { throw new NotFoundException(`CMS content with ID ${id} not found`); } const updated = await this.prisma.cmsContent.update({ where: { id }, data: dto, }); if ( typeof dto.isPublished === 'boolean' && existing.isPublished !== dto.isPublished ) { this.audit.log({ action: dto.isPublished ? AuditAction.CMS_BLOG_PUBLISH : AuditAction.CMS_BLOG_UNPUBLISH, resourceType: 'CmsContent', resourceId: id, metadata: { pageSlug: existing.pageSlug, sectionKey: existing.sectionKey }, }); } return updated; } async remove(id: string) { const existing = await this.prisma.cmsContent.findUnique({ where: { id } }); if (!existing) { throw new NotFoundException(`CMS content with ID ${id} not found`); } const deleted = await this.prisma.cmsContent.delete({ where: { id } }); this.audit.log({ action: AuditAction.CMS_BLOG_DELETE, resourceType: 'CmsContent', resourceId: id, metadata: { pageSlug: existing.pageSlug, sectionKey: existing.sectionKey }, }); return deleted; } }