import { Injectable } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; import { AuditLogService } from '../audit/audit-log.service'; import { SiteSettings } from '../../generated/prisma'; import { UpdateSiteSettingsDto } from './dto/update-site-settings.dto'; const SINGLETON_ID = 'singleton'; function emptyToNull(value: string | undefined): string | null { return value === '' ? null : (value ?? null); } @Injectable() export class SiteSettingsService { constructor( private readonly prisma: PrismaService, private readonly auditLog: AuditLogService, ) {} // Find-or-create rather than a migration-time seed row: keeps the // singleton pattern self-contained in this service instead of coupling it // to seed.ts/migration ordering. async get(): Promise { const existing = await this.prisma.siteSettings.findUnique({ where: { id: SINGLETON_ID }, }); if (existing) { return existing; } return this.prisma.siteSettings.create({ data: { id: SINGLETON_ID } }); } async update( dto: UpdateSiteSettingsDto, actingUserId: string, ): Promise { const before = await this.get(); const settings = await this.prisma.siteSettings.update({ where: { id: SINGLETON_ID }, data: { youtubeUrl: dto.youtubeUrl !== undefined ? emptyToNull(dto.youtubeUrl) : undefined, instagramUrl: dto.instagramUrl !== undefined ? emptyToNull(dto.instagramUrl) : undefined, tiktokUrl: dto.tiktokUrl !== undefined ? emptyToNull(dto.tiktokUrl) : undefined, }, }); await this.auditLog.record({ entityType: 'SiteSettings', entityId: SINGLETON_ID, action: 'UPDATE', userId: actingUserId, beforeData: before, afterData: settings, }); return settings; } }