using NetinaCMS.Repository.Extensions;

namespace NetinaCMS.Repository.Models;


public class ApplicationContext : IdentityDbContext<ApplicationUser, ApplicationRole, Guid>
{
    private readonly ILogger<ApplicationContext> _logger;
    private readonly Assembly _projectAssembly;

    public ApplicationContext(DbContextOptions<ApplicationContext> options, ILogger<ApplicationContext> logger) : base(options)
    {
        _logger = logger;
        _projectAssembly = options.GetExtension<DbContextOptionCustomExtensions>().ProjectAssembly;
    }


    protected override void OnModelCreating(ModelBuilder builder)
    {
        var stopwatch = new Stopwatch();
        stopwatch.Start();
        base.OnModelCreating(builder);
        var entitiesAssembly = _projectAssembly;
        builder.RegisterAllEntities<ApiEntity>(_logger, entitiesAssembly);
        stopwatch.Stop();
        _logger.LogInformation($"!!!!!!! RegisterAllEntities : {stopwatch.ElapsedMilliseconds}ms !!!!!!!");


        RenameIdentityTables(builder);
        builder.RegisterEntityTypeConfiguration(entitiesAssembly);
        builder.AddPluralizingTableNameConvention();
        builder.AddRestrictDeleteBehaviorConvention();
        //builder.AddSequentialGuidForIdConvention();
    }

    protected void RenameIdentityTables(ModelBuilder builder)
    {
        builder.HasDefaultSchema("public");

        builder.Entity<ApplicationUser>().ToTable("Users");
        builder.Entity<ApplicationRole>().ToTable("Roles");
        builder.Entity<IdentityRoleClaim<Guid>>().ToTable("RoleClaims");
        builder.Entity<IdentityUserRole<Guid>>().ToTable("UserRoles");
        builder.Entity<IdentityUserClaim<Guid>>().ToTable("Claims");
        builder.Entity<IdentityUserLogin<Guid>>().ToTable("Logins");
        builder.Entity<IdentityUserToken<Guid>>().ToTable("Tokens");

    }
}