using Microsoft.EntityFrameworkCore;

namespace DataModel.Database.Common;

public sealed class DataContext : DbContext
{
    public DbSet<Setting> Settings { get; set; }

    public DbSet<Section> Sections { get; set; }

    public DbSet<TextElement> TextElements { get; set; }

    public DbSet<Translation> Translations { get; set; }

    public DataContext(DbContextOptions<DataContext> contextOptions) : base(contextOptions)
    {
    }
    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        #region Settings
        
        modelBuilder.Entity<Setting>().HasIndex(n => n.Id);
        modelBuilder.Entity<Setting>().HasIndex(n => n.Name).IsUnique();
        modelBuilder.Entity<Setting>().HasIndex(n => n.BoolValue);
        modelBuilder.Entity<Setting>().HasIndex(n => n.GuidValue);
        modelBuilder.Entity<Setting>().HasIndex(n => n.IntegerValue);
        modelBuilder.Entity<Setting>().HasIndex(n => n.TextValue);

        #endregion

        #region Sections

        modelBuilder.Entity<Section>().HasIndex(n => n.Id);
        modelBuilder.Entity<Section>().HasIndex(n => n.Name);
        modelBuilder.Entity<Section>().HasIndex(n => n.Depth);
        modelBuilder.Entity<Section>().HasIndex(n => n.DataKey);
        // modelBuilder.Entity<Section>().Navigation(n => n.Parent).AutoInclude(); // Cycle-reference, does not work, though.
        modelBuilder.Entity<Section>().Navigation(n => n.TextElements).AutoInclude();

        #endregion

        #region TextElements

        modelBuilder.Entity<TextElement>().HasIndex(n => n.Id);
        modelBuilder.Entity<TextElement>().HasIndex(n => n.Code);
        modelBuilder.Entity<TextElement>().HasIndex(n => n.Name);
        modelBuilder.Entity<TextElement>().Navigation(n => n.Section).AutoInclude();

        #endregion

        #region Translations

        modelBuilder.Entity<Translation>().HasIndex(n => n.Id);
        modelBuilder.Entity<Translation>().HasIndex(n => n.Culture);
        modelBuilder.Entity<Translation>().HasIndex(n => n.Text);
        modelBuilder.Entity<Translation>().Navigation(n => n.TextElement).AutoInclude();

        #endregion
    }
}