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

namespace ERPCore.Infra.Persistence.Configurations;

public sealed class SubCategoryConfiguration : IEntityTypeConfiguration<SubCategory>
{
    public void Configure(EntityTypeBuilder<SubCategory> builder)
    {
        builder.ToTable("subcategories");
        builder.HasKey(s => s.SubCategoryId);

        builder.Property(s => s.Name).IsRequired().HasMaxLength(200);

        builder.Property(s => s.Status)
            .HasConversion<string>().HasMaxLength(20).IsRequired()
            .HasDefaultValue(EntityStatus.Active);

        builder.Property(s => s.CreatedAt).IsRequired();

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

        builder.HasOne(s => s.Category)
            .WithMany(c => c.SubCategories)
            .HasForeignKey(s => s.CategoryId)
            .OnDelete(DeleteBehavior.Restrict);

        // Names need only be unique within their parent category.
        builder.HasIndex(s => new { s.CategoryId, s.Name }).IsUnique();
        builder.HasIndex(s => s.Status);
    }
}
