/** * Settings store — simplified. Only global basics live here. * Recipients/channels are now "Monitoring Pages" (stored in their own table). */ import { db } from "@/lib/db"; export type SaleType = "auction" | "sale"; export interface AppSettings { botToken: string; // Monitoring (global) intervalSeconds: number; realtimeMode: boolean; minBidTon: number; // global min bid (pages can override) maxBidTon: number; // global max bid to fetch (0 = unlimited) // Data sources sourceFragment: boolean; sourceGetgems: boolean; sourceMock: boolean; fetchSaleType: "auction" | "sale" | "both"; // Global default message template (pages can override) messageTemplate: string; } export const DEFAULT_SETTINGS: AppSettings = { botToken: "", intervalSeconds: 60, realtimeMode: false, minBidTon: 0, maxBidTon: 0, sourceFragment: true, sourceGetgems: true, sourceMock: true, fetchSaleType: "auction", messageTemplate: "🔨 مزاد جديد على المعرف\n\n" + "👤 المعرف: @{username}\n" + "💰 تم وضع مزاد بقيمة: {bid} TON\n" + "⏳ ينتهي خلال: {timeLeft}\n" + "🔗 {url}", }; const SETTINGS_ID = "app"; export async function getSettings(): Promise { const row = await db.setting.findUnique({ where: { id: SETTINGS_ID } }); if (!row) { await db.setting.create({ data: { id: SETTINGS_ID, value: JSON.stringify(DEFAULT_SETTINGS) } }); return { ...DEFAULT_SETTINGS }; } try { const parsed = JSON.parse(row.value) as Partial; const merged: AppSettings = { ...DEFAULT_SETTINGS, ...parsed }; // Migration: remove deprecated fields return merged; } catch { return { ...DEFAULT_SETTINGS }; } } export async function saveSettings(next: Partial): Promise { const current = await getSettings(); const clean: Partial = {}; for (const [k, v] of Object.entries(next)) { if (v !== undefined) (clean as Record)[k] = v; } const merged: AppSettings = { ...current, ...clean }; await db.setting.upsert({ where: { id: SETTINGS_ID }, create: { id: SETTINGS_ID, value: JSON.stringify(merged) }, update: { value: JSON.stringify(merged) }, }); return merged; } export function formatMessage( template: string, data: { username: string; bid: number; source: string; pattern?: string; url?: string; timeLeft?: string; saleType?: string; } ): string { const saleLabel = data.saleType === "sale" ? "بيع مباشر" : "مزاد"; return (template || "") .replace(/\{username\}/g, data.username) .replace(/\{bid\}/g, String(data.bid)) .replace(/\{source\}/g, data.source) .replace(/\{pattern\}/g, data.pattern || "—") .replace(/\{url\}/g, data.url || "—") .replace(/\{timeLeft\}/g, data.timeLeft || "—") .replace(/\{saleType\}/g, saleLabel); }