﻿using Dapper;
using DapperTest.Models.Domain;
using System;
using System.Data;
using System.Data.SqlClient;

namespace DapperTest.Repositories
{
    public class TestableBaseRepository<T> : BaseRepository<T>, IDisposable where T : DomainBase
    {
        private SqlConnection _connection;
        private IDbTransaction _transaction;

        public TestableBaseRepository(SqlConnection connection) : base(connection)
        {
            _connection = connection;
            _transaction = connection.BeginTransaction();           
        }

        public void Update(string sql)
        {
            _connection.Execute(sql, transaction: _transaction);
        }

        public void Rollback()
        {            
            _transaction.Rollback();
        }

        public void Dispose()
        {
            if(_transaction != null)
            {
                Rollback();
            }

            if(_connection != null)
            {
                _connection.Close();
            }
        }
    }
}
