namespace MyOffice.DbContext;

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

public record ConnectionConfiguration(string Provider, string ConnectionString);

public class RepositoryInitializer
{
	public static void Initialize(
		IServiceCollection services,
		ConnectionConfiguration connectionString
	)
	{
		Services = services!;
		ConnectionString = connectionString;

		var db = AppDbContextFactory.Instance.CreateDbContext();
		db.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
		db.Database.Migrate();
		Prefill(db);
	}

	public static ConnectionConfiguration ConnectionString { get; internal set; } = null!;
	public static IServiceCollection Services { get; internal set; } = null!;

	private static void Prefill(AppDbContext dbContext)
	{
		// CurrencyGlobals
		var predefinedCurrencyGlobals = new List<CurrencyGlobal>()
		{
			new() { Id = "UAH", DefaultQuantity = 1, Symbol = "₴", Name = "Ukrainian hryvnias" },
			new() { Id = "USD", DefaultQuantity = 1, Symbol = "$", Name = "US Dollar" },
			new() { Id = "EUR", DefaultQuantity = 1, Symbol = "€", Name = "Euros" },
			new() { Id = "GBP", DefaultQuantity = 1, Symbol = "£", Name = "British pounds sterling" },
			new() { Id = "RUB", DefaultQuantity = 10, Symbol = "₽", Name = "Russia Ruble" },
		};

		var currencyGlobals = dbContext.CurrencyGlobals.ToList();
		foreach (var predefined in predefinedCurrencyGlobals)
		{
			if (currencyGlobals.FirstOrDefault(x => x.Id == predefined.Id) == null)
			{
				dbContext.CurrencyGlobals.Add(predefined);
			}
		}

		dbContext.SaveChanges();
	}
}