using ERPCore.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace ERPCore.Infra.Persistence.Configurations;

/// <summary>
/// Configures the singleton product-configuration row (FR-MD-11). The check constraint
/// is what makes "singleton" a database guarantee rather than a convention.
/// </summary>
public sealed class ProductConfigConfiguration : IEntityTypeConfiguration<ProductConfig>
{
    public void Configure(EntityTypeBuilder<ProductConfig> builder)
    {
        // The column is created as quoted PascalCase ("ConfigId"), so the constraint must
        // quote it too — an unquoted config_id would fold to a column that does not exist.
        builder.ToTable("product_config", t =>
            t.HasCheckConstraint("ck_product_config_singleton", $"\"ConfigId\" = {ProductConfig.SingletonId}"));

        builder.HasKey(c => c.ConfigId);

        // The id is fixed, never generated — there is exactly one row, seeded by DataSeeder.
        builder.Property(c => c.ConfigId).ValueGeneratedNever();

        builder.Property(c => c.SubcategoriesEnabled).IsRequired().HasDefaultValue(true);
        builder.Property(c => c.BrandsEnabled).IsRequired().HasDefaultValue(true);
        builder.Property(c => c.ItemTypesEnabled).IsRequired().HasDefaultValue(true);

        // PostgreSQL xmin system column as the optimistic concurrency token (ETag).
        builder.Property(c => c.RowVersion).IsRowVersion();

        builder.HasOne(c => c.UpdatedByUser)
            .WithMany()
            .HasForeignKey(c => c.UpdatedBy)
            .OnDelete(DeleteBehavior.Restrict);
    }
}
