import { FileBackupStorage } from '@buzztrail/accounts-backup'; import { logger } from '../utils/logger'; export class DatabaseService { private static instance: DatabaseService; private backupStorage: FileBackupStorage; private isInitialized = false; private constructor() { // Initialize with file-based backup storage this.backupStorage = new FileBackupStorage('./backup-data'); } static getInstance(): DatabaseService { if (!DatabaseService.instance) { DatabaseService.instance = new DatabaseService(); } return DatabaseService.instance; } async initialize(): Promise { if (this.isInitialized) { return; } try { logger.info('Initializing DatabaseService for fake server...'); // File-based storage initialization // The FileBackupStorage will load existing backup data this.isInitialized = true; logger.info('DatabaseService initialized successfully with file-based storage'); } catch (_error) { logger.error('Failed to initialize DatabaseService:', error); throw error; } } // Get backup data (file-based approach) async getAllCustomers() { try { const customers = await this.backupStorage.getAvailableCustomers(); return customers.map(customer => ({ customer_id: customer.customer_id, customer_name: customer.customer_name })); } catch (_error) { logger.error('Error getting customers:', error); return []; } } async getCustomerById(_customerId: string) { try { const customers = await this.backupStorage.getAvailableCustomers(); const customer = customers.find(c => c.customer_id === customerId); return customer ? { customer_id: customer.customer_id, customer_name: customer.customer_name } : null; } catch (_error) { logger.error('Error getting customer:', error); return null; } } async createCustomer(customerData: { customer_name: string; vapi_org_id?: string }) { // In file-based system, customers are created when backups are stored logger.info(`Customer ${customerData.customer_name} will be created when backup data is stored`); return { customer_id: customerData.customer_name, customer_name: customerData.customer_name }; } updateCustomer(_customerId: string, _customerData: Partial<{ customer_name: string; vapi_org_id: string; is_active: boolean }>) { // Note: DatabaseManager doesn't have updateCustomer method throw new Error('Update customer not implemented in DatabaseManager'); } deleteCustomer(_customerId: string) { // Note: DatabaseManager doesn't have deleteCustomer method throw new Error('Delete customer not implemented in DatabaseManager'); } // Tavus account management getAllTavusAccounts() { // Note: DatabaseManager doesn't have getAllTavusAccounts method throw new Error('Get all Tavus accounts not implemented in DatabaseManager'); } async getTavusAccountsByCustomer(_customerId: string) { // File-based storage: extract account info from backup data try { const customerBackups = await this.backupStorage.getCustomerBackups(customerId); if (customerBackups.length === 0) { return []; } const latestBackup = customerBackups.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0]; const backupData = await this.backupStorage.loadTavusBackupData(customerId, latestBackup.created_at); return backupData?.account_info ? [backupData.account_info] : []; } catch (_error) { logger.error('Error getting Tavus accounts:', error); return []; } } async createTavusAccount(_accountData: { customer_id: string; account_type: 'production' | 'testing'; tavus_account_id: string; tavus_api_key: string; account_name: string; }) { // File-based storage: accounts are part of backup data, return mock response logger.info('File-based storage: Tavus account creation handled by backup service'); return { account_id: 'mock-account-' + Date.now(), ...accountData, created_at: new Date().toISOString() }; } updateTavusAccount(_accountId: string, _accountData: Partial<{ account_type: 'production' | 'testing'; tavus_account_id: string; tavus_api_key: string; account_name: string; is_active: boolean; }>) { // Note: DatabaseManager doesn't have updateTavusAccount method throw new Error('Update Tavus account not implemented in DatabaseManager'); } deleteTavusAccount(_accountId: string) { // Note: DatabaseManager doesn't have deleteTavusAccount method throw new Error('Delete Tavus account not implemented in DatabaseManager'); } // Real persona management (file-based) async getAllRealPersonas() { try { const backups = await this.backupStorage.getAllBackups(); const allPersonas = []; for (const backup of backups) { const backupData = await this.backupStorage.loadTavusBackupData(backup.customer_id, backup.created_at); if (backupData?.personas) { allPersonas.push(...backupData.personas.map(p => ({ ...p, customer_id: backup.customer_id }))); } } return allPersonas; } catch (_error) { logger.error('Error getting all personas:', error); return []; } } async getRealPersonasByCustomer(_customerId: string) { try { const customerBackups = await this.backupStorage.getCustomerBackups(customerId); if (customerBackups.length === 0) { return []; } // Get the most recent backup const latestBackup = customerBackups.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0]; const backupData = await this.backupStorage.loadTavusBackupData(customerId, latestBackup.created_at); return backupData?.personas || []; } catch (_error) { logger.error('Error getting customer personas:', error); return []; } } async getRealPersonasByAccount(tavusAccountId: string) { // For file-based storage, we need to search through all backups try { const allPersonas = await this.getAllRealPersonas(); return allPersonas.filter(p => p.account_id === tavusAccountId); } catch (_error) { logger.error('Error getting personas by account:', error); return []; } } async upsertRealPersona(personaData: { customer_id: string; tavus_account_id: string; real_persona_id: string; name: string; description: string; avatar_url?: string; voice_id?: string; }) { // File-based storage is read-only for backups logger.info('File-based storage: persona upsert not supported, data is read-only'); return personaData; } deleteRealPersona(_personaId: string) { // Note: DatabaseManager doesn't have deleteRealPersona method throw new Error('Delete real persona not implemented in DatabaseManager'); } // Sync log management getAllSyncLogs() { // Note: DatabaseManager doesn't have getAllSyncLogs method throw new Error('Get all sync logs not implemented in DatabaseManager'); } getSyncLogsByCustomer(_customerId: string) { // Note: DatabaseManager doesn't have getSyncLogsByCustomer method throw new Error('Get sync logs by customer not implemented in DatabaseManager'); } createSyncLog(_logData: { customer_id: string; tavus_account_id: string; entity_type: string; sync_direction: 'tavus_to_local' | 'local_to_tavus'; entity_count: number; }) { // File-based storage: sync logs not supported, return mock response logger.info('File-based storage: sync log creation not supported'); return { log_id: 'mock-sync-log-' + Date.now(), ...logData, sync_status: 'in_progress', created_at: new Date().toISOString() }; } updateSyncLog(_logId: string, _logData: Partial<{ sync_completed_at: string; sync_status: 'success' | 'failed' | 'in_progress'; error_message: string; }>) { // Note: DatabaseManager doesn't have updateSyncLog method throw new Error('Update sync log not implemented in DatabaseManager'); } // Backup management getAllBackups() { // Note: DatabaseManager doesn't have getAllBackups method throw new Error('Get all backups not implemented in DatabaseManager'); } async getBackupsByCustomer(_customerId: string) { return await this.backupStorage.getCustomerBackups(customerId); } async createBackup(backupData: { customer_id: string; service: string; backup_type: string; file_path: string; file_size: number; checksum: string; expires_at?: string; metadata?: Record; }) { // File-based storage: backups are created via saveTavusBackup method logger.info('File-based storage: backup creation handled by backup service'); return { backup_id: 'mock-backup-' + Date.now(), ...backupData, created_at: new Date().toISOString() }; } deleteBackup(_backupId: string) { // Note: DatabaseManager doesn't have deleteBackup method // This would need to be implemented if needed throw new Error('Delete backup not implemented in DatabaseManager'); } // Utility methods getDatabaseStats() { // Note: DatabaseManager doesn't have getDatabaseStats method // Return basic stats if needed return { message: 'Database stats not implemented in DatabaseManager', connected: true }; } closeDatabase() { // File-based storage doesn't need explicit closing logger.info('File-based storage: no explicit close needed'); } } export default DatabaseService;