import { Sequelize, Transaction } from "sequelize";
import { TBusinessTransaction } from "../../domain";
import { InfrastructureError } from "../InfrastructureError";

export type SequelizeBusinessTransactionType = TBusinessTransaction & {
  complete<T>(work: (t: Transaction) => Promise<T>): Promise<T>;
};

export class SequelizeBusinessTransaction
  implements SequelizeBusinessTransactionType
{
  private _connection: Sequelize;

  constructor(connection: Sequelize) {
    this._connection = connection;
  }

  public start(): void {
    return;
  }

  public async complete<T>(work: (t: Transaction) => Promise<T>): Promise<T> {
    try {
      return await this._connection.transaction(work);
    } catch (error: unknown) {
      //error instanceof BaseError;
      throw InfrastructureError.create(
        InfrastructureError.UNEXCEPTED_ERROR,
        (error as Error).message,
      );
    }
  }
}
