using Elwig;
using Elwig.Helpers;
using Elwig.Helpers.Billing;
using Microsoft.Data.Sqlite;
using System.Reflection;

namespace Tests {
    [SetUpFixture]
    public class DatabaseSetup {

        private SqliteConnection? Connection;

        [OneTimeSetUp]
        public async Task Setup_1_Database() {
            AppDbContext.ConnectionStringOverride = $"Data Source=ElwigTestDB; Mode=Memory; Foreign Keys=True; Cache=Shared";
            Connection = await AppDbContext.ConnectAsync();
            await Connection.ExecuteEmbeddedScript(Assembly.GetExecutingAssembly(), "Tests.Resources.Sql.Create.sql");
            await Connection.ExecuteEmbeddedScript(Assembly.GetExecutingAssembly(), "Tests.Resources.Sql.Insert.sql");
        }

        [OneTimeSetUp]
        public void Setup_2_Client() {
            using var ctx = new AppDbContext();
            App.Client = new ClientParameters(ctx);
            App.SetBranch(ctx.Branches.Single());
        }

        [OneTimeSetUp]
        public async Task Setup_3_BillingData() {
            await BillingData.Init();
        }

        [OneTimeSetUp]
        public void Setup_4_Culture() {
            Utils.OverrideCulture();
        }

        [OneTimeTearDown]
        public async Task TeardownDatabase() {
            AppDbContext.ConnectionStringOverride = null;
            if (Connection == null) return;
            await Connection.DisposeAsync();
            Connection = null;
            // The in-memory database will be dropped if all connections to it are closed
        }
    }
}
