using Baya.Domain.Entities.User;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Baya.Infrastructure.Persistence.Configuration.UserConfig;

internal sealed class UserSessionConfig : IEntityTypeConfiguration<UserSession>
{
    public void Configure(EntityTypeBuilder<UserSession> builder)
    {
        builder.ToTable("UserSessions", "usr");

        builder.Property(s => s.RefreshTokenHash).HasMaxLength(128).IsRequired();
        builder.Property(s => s.DeviceInfo).HasMaxLength(400);
        builder.Property(s => s.IpAddress).HasMaxLength(64);
        builder.Property(s => s.IsRevoked).HasDefaultValue(false);

        // Rotation looks sessions up by the presented token's hash; revoke-all scans by (user, active).
        builder.HasIndex(s => s.RefreshTokenHash).IsUnique();
        builder.HasIndex(s => new { s.UserId, s.IsRevoked });

        builder.HasOne(s => s.User).WithMany(u => u.Sessions).HasForeignKey(s => s.UserId);

        // Mirrors the owner's soft-delete filter so a deleted user's sessions are unreachable.
        builder.HasQueryFilter(s => s.User.DeletedAt == null);
    }
}