using Baya.Domain.Entities.Geography;
using Baya.Domain.Entities.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Baya.Infrastructure.Persistence.Configuration.IdentityConfig;

internal sealed class CustomerAddressConfig : IEntityTypeConfiguration<CustomerAddress>
{
    public void Configure(EntityTypeBuilder<CustomerAddress> builder)
    {
        builder.ToTable("CustomerAddresses", "usr");

        builder.Property(a => a.Title).HasMaxLength(100).IsRequired();

        // address_line, postal_code and recipient contact are encrypted at rest (converters wired in
        // ApplicationDbContext). The title and coordinates are not PII and stay plaintext.
        builder.Property(a => a.Latitude).HasPrecision(9, 6);
        builder.Property(a => a.Longitude).HasPrecision(9, 6);
        builder.Property(a => a.GeocodeSource).HasMaxLength(20);
        builder.Property(a => a.IsPrimary).HasDefaultValue(false);

        // Exactly one primary address per customer — the authoritative DB backstop the set-primary
        // transaction must never trip. Excludes soft-deleted rows.
        builder.HasIndex(a => a.CustomerId)
            .IsUnique()
            .HasFilter("[IsPrimary] = 1 AND [DeletedAt] IS NULL")
            .HasDatabaseName("UX_CustomerAddresses_Customer_Primary");

        builder.HasOne(a => a.Customer)
            .WithMany()
            .HasForeignKey(a => a.CustomerId)
            .IsRequired();

        builder.HasOne(a => a.City)
            .WithMany()
            .HasForeignKey(a => a.CityId)
            .IsRequired();

        builder.HasOne(a => a.District)
            .WithMany()
            .HasForeignKey(a => a.DistrictId)
            .IsRequired(false);

        builder.HasQueryFilter(a => a.DeletedAt == null);
    }
}
