using System.IO;
using System.Threading.Tasks;
using Lucca.Upgrading.Abstractions;
using Lucca.Upgrading.Discovery;
using Lucca.Upgrading.Extensions;
using Lucca.Upgrading.Test.EfDb;
using Xunit;

namespace Lucca.Upgrading.Test
{
    public class SqlStepsErrorTests
    {
        public SqlStepsErrorTests()
        {
            _sqlUpdateStepDiscoveryService = new SqlUpdateStepDiscoveryService();
        }
         
        private const string _connectionString = @"Server=(localdb)\v11.0;Integrated Security=true;Initial Catalog=ErrorTestDb;Connection Timeout=30;";

        private readonly SqlUpdateStepDiscoveryService _sqlUpdateStepDiscoveryService;

        [Fact]
        public async Task SqlStatementError()
        {
            var dbName = "ErrorTestDb";
            SqlHelper.CreateDatabase(dbName);
            try
            {
                string dir = Directory.GetCurrentDirectory();
                string sqlFodler = Path.Combine(dir, "SqlErrorFiles");

                var updater = new Updater(_sqlUpdateStepDiscoveryService.Yield(), new EfRepository(_connectionString));
                updater.Settings.ConnectionString = _connectionString;
                updater.Settings.ScriptFolder = sqlFodler;

                Batch batch = updater.Prepare();
                Assert.NotNull(batch);
                Assert.NotNull(batch.Steps);
                UpdateReport report = await updater.RunUpdater(batch);
                Assert.NotNull(report);
                Assert.NotNull(report.Reports);
                Assert.False(report.Success);
            }
            finally
            {
                SqlHelper.DropDatabase(dbName);
            }
        }
    }
}