using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using SolutionErp.Domain.Contracts;

namespace SolutionErp.Infrastructure.Persistence.Configurations;

public class ContractChangelogConfiguration : IEntityTypeConfiguration<ContractChangelog>
{
    public void Configure(EntityTypeBuilder<ContractChangelog> b)
    {
        b.ToTable("ContractChangelogs");
        b.HasKey(x => x.Id);

        b.Property(x => x.EntityType).HasConversion<int>();
        b.Property(x => x.Action).HasConversion<int>();
        b.Property(x => x.PhaseAtChange).HasConversion<int?>();
        b.Property(x => x.UserName).HasMaxLength(200);
        b.Property(x => x.Summary).HasMaxLength(500);
        b.Property(x => x.FieldChangesJson).HasColumnType("nvarchar(max)");
        b.Property(x => x.ContextNote).HasMaxLength(2000);

        b.HasOne(x => x.Contract)
            .WithMany(c => c.Changelogs)
            .HasForeignKey(x => x.ContractId)
            .OnDelete(DeleteBehavior.Cascade);

        // Common queries: all changes của 1 HĐ ordered timeline
        b.HasIndex(x => new { x.ContractId, x.CreatedAt });
        // Filter theo entity type (chỉ xem header changes / chỉ workflow / etc.)
        b.HasIndex(x => new { x.ContractId, x.EntityType });
    }
}
