using CartWise.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace CartWise.Infrastructure.Data.Configurations;

public class PriceObservationConfiguration : IEntityTypeConfiguration<PriceObservation>
{
    public void Configure(EntityTypeBuilder<PriceObservation> builder)
    {
        builder.HasKey(o => o.PriceObservationId);

        builder.Property(o => o.CurrencyCode)
            .HasMaxLength(3)
            .IsRequired();

        builder.Property(o => o.SourceReference)
            .HasMaxLength(200);

        builder.HasOne<Household>()
            .WithMany()
            .HasForeignKey(o => o.HouseholdId)
            .OnDelete(DeleteBehavior.SetNull);

        // Restrict, not Cascade: PriceObservation is append-only history and must never be
        // silently destroyed by deleting the Product it references.
        builder.HasOne<Product>()
            .WithMany()
            .HasForeignKey(o => o.ProductId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasOne<StoreLocation>()
            .WithMany()
            .HasForeignKey(o => o.StoreLocationId)
            .OnDelete(DeleteBehavior.SetNull);

        builder.HasIndex(o => new { o.ProductId, o.ObservedUtc });
        builder.HasIndex(o => new { o.ProductId, o.StoreLocationId, o.ObservedUtc });
        builder.HasIndex(o => new { o.HouseholdId, o.ProductId, o.ObservedUtc });
    }
}
