namespace MyOffice.DbContext;

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;

public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
	public static AppDbContextFactory Instance = new();

	public AppDbContext CreateDbContext()
	{
		return CreateDbContext(null);
	}

	public AppDbContext CreateDbContext(string[]? args)
	{
		var connection = RepositoryInitializer.ConnectionString;
		if (connection is null)
		{
			connection = new ConnectionConfiguration(
				args?[0] ?? "npgsql",
				args?[1] ?? string.Empty);
		}

		var builder = new DbContextOptionsBuilder<AppDbContext>();
		DbContextServiceCollectionExtensions.ConfigureDbContextOptions(builder, connection);

		if (!Enum.TryParse<AppDbContextProvidersEnum>(connection?.Provider ?? args?[0] ?? "", ignoreCase: true, out var providerEnum))
			throw new InvalidOperationException($"No such provider: [{connection?.Provider}]");

		var db = new AppDbContext(providerEnum, builder.Options);
		db.ChangeTracker.AutoDetectChangesEnabled = false;
		db.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
		
		return db;
	}
}