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

namespace CartWise.Infrastructure.Data.Configurations;

public class ProductConfiguration : IEntityTypeConfiguration<Product>
{
    public void Configure(EntityTypeBuilder<Product> builder)
    {
        builder.HasKey(p => p.ProductId);

        builder.Property(p => p.Name)
            .HasMaxLength(240)
            .IsRequired();

        builder.Property(p => p.NormalizedName)
            .HasMaxLength(240)
            .IsRequired();

        builder.Property(p => p.SizeUnit)
            .HasMaxLength(32);

        builder.Property(p => p.SourceExternalId)
            .HasMaxLength(200);

        builder.HasIndex(p => p.NormalizedName);

        builder.HasOne<GroceryConcept>()
            .WithMany()
            .HasForeignKey(p => p.GroceryConceptId)
            .OnDelete(DeleteBehavior.SetNull);

        builder.HasOne<Brand>()
            .WithMany()
            .HasForeignKey(p => p.BrandId)
            .OnDelete(DeleteBehavior.SetNull);

        builder.Metadata.FindNavigation(nameof(Product.Identifiers))!
            .SetPropertyAccessMode(PropertyAccessMode.Field);
    }
}
