using Heimdall.Domain.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System.Text.Json; namespace Heimdall.Infrastructure.Data.Configurations; public class KnownFaceConfiguration : IEntityTypeConfiguration { private static readonly JsonSerializerOptions JsonOptions = new(); public void Configure(EntityTypeBuilder builder) { builder.ToTable("known_faces"); builder.HasKey(f => f.Id); builder.Property(f => f.ThumbnailUrl) .HasMaxLength(2000) .IsUnicode(false); builder.Property(f => f.SourceEventId) .HasMaxLength(100) .IsUnicode(false); // Store float[] as JSONB with graceful fallback on corrupt data builder.Property(f => f.Embedding) .HasColumnType("jsonb") .HasConversion( v => JsonSerializer.Serialize(v, JsonOptions), v => DeserializeEmbedding(v)) .Metadata.SetValueComparer(new ValueComparer( (a, b) => (a == null && b == null) || (a != null && b != null && a.SequenceEqual(b)), v => v.Aggregate(0, (hash, val) => HashCode.Combine(hash, val.GetHashCode())), v => v.ToArray())); builder.HasIndex(f => f.PersonId); } private static float[] DeserializeEmbedding(string json) { try { return JsonSerializer.Deserialize(json, JsonOptions) ?? Array.Empty(); } catch (JsonException) { return Array.Empty(); } } }