import { getLogger } from '@stock-bot/logger';
import type { PostgreSQLClient } from './client';
import type { TransactionCallback } from './types';

/**
 * PostgreSQL Transaction Manager
 *
 * Provides transaction support for multi-statement operations
 */
export class PostgreSQLTransactionManager {
  private readonly client: PostgreSQLClient;
  private readonly logger: ReturnType<typeof getLogger>;

  constructor(client: PostgreSQLClient) {
    this.client = client;
    this.logger = getLogger('postgres-transaction-manager');
  }

  /**
   * Execute operations within a transaction
   */
  async execute<T>(callback: TransactionCallback<T>): Promise<T> {
    const pool = this.client.connectionPool;
    if (!pool) {
      throw new Error('PostgreSQL client not connected');
    }

    const client = await pool.connect();

    try {
      this.logger.debug('Starting PostgreSQL transaction');

      await client.query('BEGIN');

      const result = await callback(client);

      await client.query('COMMIT');

      this.logger.debug('PostgreSQL transaction committed successfully');
      return result;
    } catch (error) {
      this.logger.error('PostgreSQL transaction failed, rolling back:', error);

      try {
        await client.query('ROLLBACK');
      } catch (rollbackError) {
        this.logger.error('Failed to rollback transaction:', rollbackError);
      }

      throw error;
    } finally {
      client.release();
    }
  }
}
