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

namespace ERPCore.Infra.Persistence.Configurations;

public sealed class UserConfiguration : IEntityTypeConfiguration<User>
{
    public void Configure(EntityTypeBuilder<User> builder)
    {
        builder.ToTable("users");
        builder.HasKey(u => u.UserId);

        builder.Property(u => u.Username).IsRequired().HasMaxLength(100);
        builder.HasIndex(u => u.Username).IsUnique();
        builder.Property(u => u.DisplayName).IsRequired().HasMaxLength(200);
        builder.Property(u => u.Status)
            .HasConversion<string>().HasMaxLength(20).IsRequired();

        // Maps the local shadow user to its AuthHex identity (unique; NULL for the
        // system user — Postgres allows multiple NULLs in a unique index).
        builder.Property(u => u.AuthUserId).HasColumnName("auth_user_id");
        builder.HasIndex(u => u.AuthUserId).IsUnique();

        // Seeded fallback audit actor while auth is deferred (§6).
        builder.HasData(new User
        {
            UserId = User.SystemUserId,
            Username = "system",
            DisplayName = "System",
            Status = EntityStatus.Active
        });
    }
}
