import { db } from '@/lib/db'; import { settings } from '@/lib/db/schema'; import { eq } from 'drizzle-orm'; export interface AppConfig { clubName: string; sportName: string; appTitle: string; appDescription: string; } const defaultConfig: AppConfig = { clubName: 'TT Club', sportName: 'Table Tennis', appTitle: 'Table Tennis Booking System', appDescription: 'Book your table tennis court slots with ease', }; let cachedConfig: AppConfig | null = null; let cacheTime: number = 0; const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes /** * Get app configuration with caching * This function fetches the club/brand settings from the database */ export async function getAppConfig(): Promise { const now = Date.now(); // Return cached config if still valid if (cachedConfig && now - cacheTime < CACHE_DURATION) { return cachedConfig; } try { // Fetch all brand/club settings const configSettings = await db .select() .from(settings) .where(eq(settings.key, 'club_name')) .union(db.select().from(settings).where(eq(settings.key, 'sport_name'))) .union(db.select().from(settings).where(eq(settings.key, 'app_title'))) .union(db.select().from(settings).where(eq(settings.key, 'app_description'))); // Build config object const config: AppConfig = { ...defaultConfig }; configSettings.forEach((setting) => { switch (setting.key) { case 'club_name': config.clubName = setting.value; break; case 'sport_name': config.sportName = setting.value; break; case 'app_title': config.appTitle = setting.value; break; case 'app_description': config.appDescription = setting.value; break; } }); // Cache the result cachedConfig = config; cacheTime = now; return config; } catch (error) { console.error('Error fetching app config:', error); // Return default config on error return defaultConfig; } } /** * Invalidate the cache (call when settings are updated) */ export function invalidateAppConfigCache() { cachedConfig = null; cacheTime = 0; } /** * Get app config for client components (no database access) * This should be used with server-side rendered props */ export function getDefaultAppConfig(): AppConfig { return { ...defaultConfig }; }