using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using TakeoutSaaS.Domain.Dictionary.Entities;
using TakeoutSaaS.Domain.SystemParameters.Entities;
using TakeoutSaaS.Infrastructure.Common.Persistence;
using TakeoutSaaS.Shared.Abstractions.Ids;
using TakeoutSaaS.Shared.Abstractions.Security;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Infrastructure.Dictionary.Persistence;

/// <summary>
/// 参数字典 DbContext：承载字典与系统参数。
/// </summary>
public sealed class DictionaryDbContext(
    DbContextOptions<DictionaryDbContext> options,
    ITenantProvider tenantProvider,
    ICurrentUserAccessor? currentUserAccessor = null,
    IIdGenerator? idGenerator = null)
    : TenantAwareDbContext(options, tenantProvider, currentUserAccessor, idGenerator)
{
    /// <summary>
    /// 字典分组集合。
    /// </summary>
    public DbSet<DictionaryGroup> DictionaryGroups => Set<DictionaryGroup>();

    /// <summary>
    /// 字典项集合。
    /// </summary>
    public DbSet<DictionaryItem> DictionaryItems => Set<DictionaryItem>();

    /// <summary>
    /// 系统参数集合。
    /// </summary>
    public DbSet<SystemParameter> SystemParameters => Set<SystemParameter>();

    /// <summary>
    /// 配置实体模型。
    /// </summary>
    /// <param name="modelBuilder">模型构建器。</param>
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        ConfigureGroup(modelBuilder.Entity<DictionaryGroup>());
        ConfigureItem(modelBuilder.Entity<DictionaryItem>());
        ConfigureSystemParameter(modelBuilder.Entity<SystemParameter>());
        ApplyTenantQueryFilters(modelBuilder);
    }

    /// <summary>
    /// 配置字典分组。
    /// </summary>
    /// <param name="builder">实体构建器。</param>
    private static void ConfigureGroup(EntityTypeBuilder<DictionaryGroup> builder)
    {
        builder.ToTable("dictionary_groups");
        builder.HasKey(x => x.Id);
        builder.Property(x => x.TenantId).IsRequired();
        builder.Property(x => x.Code).HasMaxLength(64).IsRequired();
        builder.Property(x => x.Name).HasMaxLength(128).IsRequired();
        builder.Property(x => x.Scope).HasConversion<int>().IsRequired();
        builder.Property(x => x.Description).HasMaxLength(512);
        builder.Property(x => x.IsEnabled).HasDefaultValue(true);
        ConfigureAuditableEntity(builder);
        ConfigureSoftDeleteEntity(builder);

        builder.HasIndex(x => x.TenantId);
        builder.HasIndex(x => new { x.TenantId, x.Code }).IsUnique();
    }

    /// <summary>
    /// 配置字典项。
    /// </summary>
    /// <param name="builder">实体构建器。</param>
    private static void ConfigureItem(EntityTypeBuilder<DictionaryItem> builder)
    {
        builder.ToTable("dictionary_items");
        builder.HasKey(x => x.Id);
        builder.Property(x => x.TenantId).IsRequired();
        builder.Property(x => x.GroupId).IsRequired();
        builder.Property(x => x.Key).HasMaxLength(64).IsRequired();
        builder.Property(x => x.Value).HasMaxLength(256).IsRequired();
        builder.Property(x => x.Description).HasMaxLength(512);
        builder.Property(x => x.SortOrder).HasDefaultValue(100);
        builder.Property(x => x.IsEnabled).HasDefaultValue(true);
        ConfigureAuditableEntity(builder);
        ConfigureSoftDeleteEntity(builder);

        builder.HasOne(x => x.Group)
            .WithMany(g => g.Items)
            .HasForeignKey(x => x.GroupId)
            .OnDelete(DeleteBehavior.Cascade);

        builder.HasIndex(x => x.TenantId);
        builder.HasIndex(x => new { x.GroupId, x.Key }).IsUnique();
    }

    /// <summary>
    /// 配置系统参数。
    /// </summary>
    /// <param name="builder">实体构建器。</param>
    private static void ConfigureSystemParameter(EntityTypeBuilder<SystemParameter> builder)
    {
        builder.ToTable("system_parameters");
        builder.HasKey(x => x.Id);
        builder.Property(x => x.TenantId).IsRequired();
        builder.Property(x => x.Key).HasMaxLength(128).IsRequired();
        builder.Property(x => x.Value).HasColumnType("text").IsRequired();
        builder.Property(x => x.Description).HasMaxLength(512);
        builder.Property(x => x.SortOrder).HasDefaultValue(100);
        builder.Property(x => x.IsEnabled).HasDefaultValue(true);
        ConfigureAuditableEntity(builder);
        ConfigureSoftDeleteEntity(builder);

        builder.HasIndex(x => x.TenantId);
        builder.HasIndex(x => new { x.TenantId, x.Key }).IsUnique();
    }
}
