import { Kysely } from 'kysely'; import { Database, IntegrationTable } from '../../../../shared/infrastructure/DatabaseConnection'; import { IIntegrationRepository } from '../../domain/ports/IIntegrationRepository'; import { Integration, IntegrationConfig, IntegrationProps } from '../../domain/entities/Integration'; import { UniqueId } from '../../../../shared/domain/UniqueId'; import { IntegrationType } from '../../domain/value-objects/IntegrationType'; export class KyselyIntegrationRepository implements IIntegrationRepository { constructor(private readonly db: Kysely) {} async save(integration: Integration): Promise { const row: IntegrationTable = { id: integration.id.toString(), name: integration.name, type: integration.type.value, enabled: integration.enabled ? 1 : 0, config_json: JSON.stringify(integration.config), created_at: integration.createdAt.getTime(), }; await this.db.insertInto('integrations').values(row).execute(); } async findById(id: string): Promise { const row = await this.db .selectFrom('integrations') .selectAll() .where('id', '=', id) .executeTakeFirst(); return row ? this.toDomain(row) : undefined; } async findAll(): Promise { const rows = await this.db .selectFrom('integrations') .selectAll() .orderBy('created_at', 'desc') .execute(); return rows.map(r => this.toDomain(r)); } async findEnabled(): Promise { const rows = await this.db .selectFrom('integrations') .selectAll() .where('enabled', '=', 1) .execute(); return rows.map(r => this.toDomain(r)); } async update(integration: Integration): Promise { await this.db .updateTable('integrations') .set({ name: integration.name, enabled: integration.enabled ? 1 : 0, config_json: JSON.stringify(integration.config), }) .where('id', '=', integration.id.toString()) .execute(); } async delete(id: string): Promise { await this.db.deleteFrom('integrations').where('id', '=', id).execute(); } private toDomain(row: IntegrationTable): Integration { const config = JSON.parse(row.config_json) as IntegrationConfig; const props: IntegrationProps = { name: row.name, type: IntegrationType.fromString(row.type), enabled: row.enabled === 1, config, createdAt: new Date(row.created_at), }; return Integration.reconstitute(props, UniqueId.from(row.id)); } }