/** * Providers Repository * Handles CRUD operations for cloud providers */ import { BaseRepository } from './base'; import { Provider, ProviderInput, RepositoryError, ErrorCodes } from '../types'; export class ProvidersRepository extends BaseRepository { protected tableName = 'providers'; protected allowedColumns = [ 'name', 'display_name', 'api_base_url', 'last_sync_at', 'sync_status', 'sync_error', ]; /** * Find provider by name */ async findByName(name: string): Promise { try { const result = await this.db .prepare('SELECT * FROM providers WHERE name = ?') .bind(name) .first(); return result || null; } catch (error) { this.logger.error('findByName failed', { name, error: error instanceof Error ? error.message : 'Unknown error' }); throw new RepositoryError( `Failed to find provider by name: ${name}`, ErrorCodes.DATABASE_ERROR, error ); } } /** * Update sync status for a provider */ async updateSyncStatus( name: string, status: 'pending' | 'syncing' | 'success' | 'error', error?: string ): Promise { try { const now = new Date().toISOString().replace('T', ' ').slice(0, 19); const result = await this.db .prepare( `UPDATE providers SET sync_status = ?, sync_error = ?, last_sync_at = ? WHERE name = ? RETURNING *` ) .bind(status, error || null, now, name) .first(); if (!result) { throw new RepositoryError( `Provider not found: ${name}`, ErrorCodes.NOT_FOUND ); } return result; } catch (error) { this.logger.error('updateSyncStatus failed', { name, status, error: error instanceof Error ? error.message : 'Unknown error' }); if (error instanceof RepositoryError) { throw error; } throw new RepositoryError( `Failed to update sync status for provider: ${name}`, ErrorCodes.DATABASE_ERROR, error ); } } /** * Get all providers with specific sync status */ async findByStatus(status: Provider['sync_status']): Promise { try { const result = await this.db .prepare('SELECT * FROM providers WHERE sync_status = ?') .bind(status) .all(); return result.results; } catch (error) { this.logger.error('findByStatus failed', { status, error: error instanceof Error ? error.message : 'Unknown error' }); throw new RepositoryError( `Failed to find providers by status: ${status}`, ErrorCodes.DATABASE_ERROR, error ); } } /** * Create or update a provider */ async upsert(data: ProviderInput): Promise { try { const existing = await this.findByName(data.name); if (existing) { return await this.update(existing.id, data); } return await this.create(data); } catch (error) { this.logger.error('upsert failed', { name: data.name, error: error instanceof Error ? error.message : 'Unknown error' }); throw new RepositoryError( `Failed to upsert provider: ${data.name}`, ErrorCodes.DATABASE_ERROR, error ); } } }