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

namespace ERPCore.Infra.Persistence.Configurations;

public sealed class RoleConfiguration : IEntityTypeConfiguration<Role>
{
    public void Configure(EntityTypeBuilder<Role> builder)
    {
        builder.ToTable("roles");
        builder.HasKey(r => r.RoleId);

        builder.Property(r => r.AuthRoleId).HasColumnName("auth_role_id").IsRequired();
        builder.HasIndex(r => r.AuthRoleId).IsUnique();

        builder.Property(r => r.Code).IsRequired().HasMaxLength(50);
        builder.HasIndex(r => r.Code).IsUnique();

        builder.Property(r => r.Name).IsRequired().HasMaxLength(200);
        builder.Property(r => r.IsSystemRole).IsRequired().HasDefaultValue(false);

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

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

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