using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using MyOffice.DbContext;

namespace MyOffice.Tests.Data;

public class DemoDataSeederTests
{
	[Fact]
	public async Task SeedIfEmpty_creates_demo_users_catalog_and_motions()
	{
		var path = Path.Combine(Path.GetTempPath(), $"myoffice-seed-{Guid.NewGuid():N}.db");
		var connection = new ConnectionConfiguration("sqlite", $"Data Source={path}");
		var options = new DbContextOptionsBuilder<AppDbContext>();
		DbContextServiceCollectionExtensions.ConfigureDbContextOptions(options, connection);

		await using (var db = new AppDbContext(AppDbContextProvidersEnum.sqlite, options.Options))
		{
			await DatabaseBootstrapper.InitializeAsync(db);

			Assert.Equal(3, await db.Users.CountAsync());
			Assert.Equal(9, await db.Currencies.CountAsync());
			Assert.Equal(9, await db.CurrencyRates.CountAsync());
			Assert.Equal(9, await db.AccountCategories.CountAsync());
			Assert.Equal(27, await db.Accounts.CountAsync());
			Assert.Equal(300, await db.Motions.CountAsync());

			var uahUser = await db.Users.SingleAsync(x => x.Email == "user_UAH@user_UAH.userUAH");
			Assert.Equal("UAH", uahUser.CurrencyId);

			var uahRates = await db.CurrencyRates
				.Include(x => x.Currency)
				.Where(x => x.Currency!.UserId == uahUser.Id)
				.ToListAsync();
			Assert.Equal(1m, uahRates.Single(x => x.Currency!.CurrencyGlobalId == "UAH").Rate);
			Assert.Equal(42m, uahRates.Single(x => x.Currency!.CurrencyGlobalId == "USD").Rate);
			Assert.Equal(50m, uahRates.Single(x => x.Currency!.CurrencyGlobalId == "EUR").Rate);

			Assert.Contains(await db.AccountCategories.Where(x => x.UserId == uahUser.Id).Select(x => x.Name).ToListAsync(),
				x => x == "Готівка");
			Assert.Contains(await db.ItemCategories.Where(x => x.UserId == uahUser.Id).Select(x => x.Name).ToListAsync(),
				x => x == "Доходи");

			await DemoDataSeeder.SeedIfEmptyAsync(db);
			Assert.Equal(3, await db.Users.CountAsync());
		}

		SqliteConnection.ClearAllPools();
		if (File.Exists(path))
		{
			File.Delete(path);
		}
	}
}
