import { Injectable, Logger } from "@nestjs/common"; import { SystemSettingsResponseDto, UpdateSystemSettingsDto, } from "./dto/system-settings.dto"; import { SystemSettingsDbService } from "./entities/db-service/system-settings.db.service"; @Injectable() export class SystemSettingsService { private readonly logger = new Logger(SystemSettingsService.name); private cache: Record | null = null; private cacheAt = 0; private readonly cacheTtlMs = 15_000; constructor(private readonly db: SystemSettingsDbService) {} private async loadGlobal(): Promise> { const now = Date.now(); if (this.cache && now - this.cacheAt < this.cacheTtlMs) { return this.cache; } let doc = await this.db.findGlobal(); if (!doc) { doc = await this.db.upsertGlobal({ $set: { externalApis: { sandHubUseLiveApi: false } }, }); this.logger.log( "Created default system_settings document (sandHubUseLiveApi=false)", ); } this.cache = doc; this.cacheAt = now; return doc; } private invalidateCache(): void { this.cache = null; this.cacheAt = 0; } /** * Whether SandHub/Tejarat live HTTP should run (`system_settings` collection). */ async isSandHubLiveEnabled(): Promise { const doc = await this.loadGlobal(); const externalApis = doc.externalApis as | { sandHubUseLiveApi?: boolean } | undefined; return externalApis?.sandHubUseLiveApi === true; } async getSettingsView(): Promise { const doc = await this.loadGlobal(); const externalApis = doc.externalApis as | { sandHubUseLiveApi?: boolean } | undefined; const sandHubUseLiveApi = externalApis?.sandHubUseLiveApi === true; return { key: String(doc.key ?? "global"), externalApis: { sandHubUseLiveApi }, sandHubMode: sandHubUseLiveApi ? "live" : "mock", }; } async updateSettings( body: UpdateSystemSettingsDto, ): Promise { const $set: Record = {}; if (body.externalApis?.sandHubUseLiveApi !== undefined) { $set["externalApis.sandHubUseLiveApi"] = body.externalApis.sandHubUseLiveApi; } if (Object.keys($set).length > 0) { await this.db.upsertGlobal({ $set }); this.invalidateCache(); this.logger.log(`System settings updated: ${JSON.stringify($set)}`); } return this.getSettingsView(); } }