/** * G8 Pricing Repository * Handles CRUD operations for G8 instance pricing data */ import { BaseRepository } from './base'; import { G8Pricing, G8PricingInput, RepositoryError, ErrorCodes } from '../types'; export class G8PricingRepository extends BaseRepository { protected tableName = 'g8_pricing'; protected allowedColumns = [ 'g8_instance_id', 'region_id', 'hourly_price', 'monthly_price', 'currency', 'available', ]; constructor(db: D1Database) { super(db); } /** * Find all pricing records for a specific G8 instance */ async findByG8Instance(g8InstanceId: number): Promise { try { const result = await this.db .prepare('SELECT * FROM g8_pricing WHERE g8_instance_id = ?') .bind(g8InstanceId) .all(); return result.results; } catch (error) { this.logger.error('findByG8Instance failed', { g8InstanceId, error: error instanceof Error ? error.message : 'Unknown error' }); throw new RepositoryError( `Failed to find pricing for G8 instance: ${g8InstanceId}`, ErrorCodes.DATABASE_ERROR, error ); } } /** * Find pricing for a specific G8 instance in a specific region */ async findByInstanceAndRegion(g8InstanceId: number, regionId: number): Promise { try { const result = await this.db .prepare('SELECT * FROM g8_pricing WHERE g8_instance_id = ? AND region_id = ?') .bind(g8InstanceId, regionId) .first(); return result || null; } catch (error) { this.logger.error('findByInstanceAndRegion failed', { g8InstanceId, regionId, error: error instanceof Error ? error.message : 'Unknown error' }); throw new RepositoryError( `Failed to find pricing for G8 instance ${g8InstanceId} in region ${regionId}`, ErrorCodes.DATABASE_ERROR, error ); } } /** * Upsert multiple G8 pricing records (batch operation) */ async upsertMany(pricingData: G8PricingInput[]): Promise { if (pricingData.length === 0) { return 0; } try { const statements = pricingData.map((pricing) => { return this.db.prepare( `INSERT INTO g8_pricing ( g8_instance_id, region_id, hourly_price, monthly_price, currency, available ) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(g8_instance_id, region_id) DO UPDATE SET hourly_price = excluded.hourly_price, monthly_price = excluded.monthly_price, currency = excluded.currency, available = excluded.available` ).bind( pricing.g8_instance_id, pricing.region_id, pricing.hourly_price, pricing.monthly_price, pricing.currency, pricing.available ); }); const successCount = await this.executeBatchCount(statements); this.logger.info('Upserted G8 pricing records', { count: successCount }); return successCount; } catch (error) { this.logger.error('upsertMany failed', { count: pricingData.length, error: error instanceof Error ? error.message : 'Unknown error' }); throw new RepositoryError( 'Failed to upsert G8 pricing records', ErrorCodes.TRANSACTION_FAILED, error ); } } }