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();

        // Employee<->User cross-link match field (docs/12-BACKEND-HRM.md A.5). Unique,
        // like AuthUserId — Postgres allows multiple NULLs in a unique index natively,
        // so employees/users without an email don't collide.
        builder.Property(u => u.Email).HasMaxLength(320);
        builder.HasIndex(u => u.Email).IsUnique();

        // Local shadow Role assignment (nullable — unset until an admin assigns one).
        builder.HasOne(u => u.Role).WithMany()
            .HasForeignKey(u => u.RoleId).OnDelete(DeleteBehavior.Restrict);

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