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

namespace CartWise.Infrastructure.Data.Configurations;

public class PurchaseConfiguration : IEntityTypeConfiguration<Purchase>
{
    public void Configure(EntityTypeBuilder<Purchase> builder)
    {
        builder.HasKey(p => p.PurchaseId);

        builder.HasOne<Household>()
            .WithMany()
            .HasForeignKey(p => p.HouseholdId)
            .OnDelete(DeleteBehavior.Cascade);

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

        builder.HasOne<ApplicationUser>()
            .WithMany()
            .HasForeignKey(p => p.PurchasedByUserId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasIndex(p => new { p.HouseholdId, p.PurchasedUtc });

        builder.Metadata.FindNavigation(nameof(Purchase.Items))!
            .SetPropertyAccessMode(PropertyAccessMode.Field);
    }
}
