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

namespace Baya.Infrastructure.Persistence.Configuration.GeographyConfig;

internal sealed class NurseServiceAreaConfig : IEntityTypeConfiguration<NurseServiceArea>
{
    public void Configure(EntityTypeBuilder<NurseServiceArea> builder)
    {
        builder.ToTable("NurseServiceAreas", "geo");

        builder.Property(a => a.IsActive).HasDefaultValue(true);

        // UNIQUE(nurse_id, city_id, district_id) that correctly rejects a duplicate whole-city row.
        // SQL Server treats NULLs as distinct, so a single unique index would wrongly allow two
        // "whole city" rows for the same nurse+city. Split into a filtered pair: one enforces at most one
        // whole-city row (district_id IS NULL), the other enforces uniqueness of city+district rows. Both
        // exclude soft-deleted rows so a removed area can be re-declared.
        builder.HasIndex(a => new { a.NurseId, a.CityId })
            .IsUnique()
            .HasFilter("[DistrictId] IS NULL AND [DeletedAt] IS NULL")
            .HasDatabaseName("UX_NurseServiceAreas_Nurse_City_WholeCity");

        builder.HasIndex(a => new { a.NurseId, a.CityId, a.DistrictId })
            .IsUnique()
            .HasFilter("[DistrictId] IS NOT NULL AND [DeletedAt] IS NULL")
            .HasDatabaseName("UX_NurseServiceAreas_Nurse_City_District");

        builder.HasOne<NurseProfile>()
            .WithMany()
            .HasForeignKey(a => a.NurseId)
            .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);
    }
}
