namespace MyOffice.DbContext;

using Data.Models.Currencies;
using Microsoft.EntityFrameworkCore;

/// <summary>
/// Migrate and seed using a DI-scoped <see cref="AppDbContext"/> (not the design-time factory).
/// </summary>
public static class DatabaseBootstrapper
{
	public static async Task InitializeAsync(AppDbContext db, CancellationToken cancellationToken = default)
	{
		await db.Database.MigrateAsync(cancellationToken);
		await PrefillAsync(db, cancellationToken);
		await DemoDataSeeder.SeedIfEmptyAsync(db, cancellationToken);
		await UpdateCurrentRatesAsync(db, cancellationToken);
	}

	private static async Task PrefillAsync(AppDbContext dbContext, CancellationToken cancellationToken)
	{
		var predefinedCurrencyGlobals = new List<CurrencyGlobal>
		{
			new() { Id = CurrencyGlobalIdEnum.UAH.ToString(), DefaultQuantity = 1, Symbol = "₴", Name = "Ukrainian hryvnias" },
			new() { Id = CurrencyGlobalIdEnum.USD.ToString(), DefaultQuantity = 1, Symbol = "$", Name = "US Dollar" },
			new() { Id = CurrencyGlobalIdEnum.EUR.ToString(), DefaultQuantity = 1, Symbol = "€", Name = "Euros" },
			new() { Id = CurrencyGlobalIdEnum.GBP.ToString(), DefaultQuantity = 1, Symbol = "£", Name = "British pounds sterling" },
			new() { Id = CurrencyGlobalIdEnum.RUB.ToString(), DefaultQuantity = 10, Symbol = "₽", Name = "Russia Ruble" },
			new() { Id = CurrencyGlobalIdEnum.BTC.ToString(), DefaultQuantity = 10, Symbol = "btc", Name = "Bitcoin" },
			new() { Id = CurrencyGlobalIdEnum.ETH.ToString(), DefaultQuantity = 10, Symbol = "eth", Name = "Ethereum" },
			new() { Id = CurrencyGlobalIdEnum.TON.ToString(), DefaultQuantity = 10, Symbol = "ton", Name = "TON" },
			new() { Id = CurrencyGlobalIdEnum.OTHER.ToString(), DefaultQuantity = 1, Symbol = "", Name = "Other" },
		};

		var currencyGlobals = await dbContext.CurrencyGlobals.ToListAsync(cancellationToken);
		foreach (var predefined in predefinedCurrencyGlobals)
		{
			if (currencyGlobals.All(x => x.Id != predefined.Id))
			{
				dbContext.CurrencyGlobals.Add(predefined);
			}
		}

		await dbContext.SaveChangesAsync(cancellationToken);
	}

	private static async Task UpdateCurrentRatesAsync(AppDbContext dbContext, CancellationToken cancellationToken)
	{
		var lastRates = await dbContext.CurrencyRates
			.Include(x => x.Currency)
			.GroupBy(x => new { x.CurrencyId },
				(key, g) => g.Where(x => x.DateTime <= DateTime.UtcNow).OrderByDescending(x => x.DateTime).First())
			.ToListAsync(cancellationToken);

		var currencies = await dbContext.Currencies.ToListAsync(cancellationToken);
		foreach (var currency in currencies)
		{
			var rate = lastRates.FirstOrDefault(x => x.CurrencyId == currency.Id);
			if (rate != null)
			{
				currency.CurrentRateId = rate.Id;
				dbContext.Attach(currency).State = EntityState.Modified;
			}
		}

		await dbContext.SaveChangesAsync(cancellationToken);
	}
}
