using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using FnbEngine.Domain.AggregatesModel.RecipeAggregate;

namespace FnbEngine.Infrastructure.EntityConfigurations;

public class RecipeEntityTypeConfiguration : IEntityTypeConfiguration<Recipe>
{
    public void Configure(EntityTypeBuilder<Recipe> builder)
    {
        builder.ToTable("recipes");
        builder.HasKey(r => r.Id);
        builder.Property(r => r.Id).HasColumnName("id").ValueGeneratedNever();
        builder.Property(r => r.ShopId).HasField("_shopId").HasColumnName("shop_id").IsRequired();
        builder.Property(r => r.ProductId).HasField("_productId").HasColumnName("product_id").IsRequired();
        builder.Property(r => r.Name).HasField("_name").HasColumnName("name").HasMaxLength(255).IsRequired();
        builder.Property(r => r.Instructions).HasField("_instructions").HasColumnName("instructions").HasMaxLength(2000);
        builder.Property(r => r.PrepTimeMinutes).HasField("_prepTimeMinutes").HasColumnName("prep_time_minutes");
        builder.Property(r => r.IsActive).HasField("_isActive").HasColumnName("is_active").HasDefaultValue(true);
        builder.Property(r => r.CreatedAt).HasField("_createdAt").HasColumnName("created_at").IsRequired();
        builder.Property(r => r.UpdatedAt).HasField("_updatedAt").HasColumnName("updated_at");

        builder.HasMany(r => r.Ingredients)
            .WithOne()
            .HasForeignKey(i => i.RecipeId)
            .OnDelete(DeleteBehavior.Cascade);

        var nav = builder.Metadata.FindNavigation(nameof(Recipe.Ingredients))!;
        nav.SetPropertyAccessMode(PropertyAccessMode.Field);

        builder.HasIndex(r => r.ShopId).HasDatabaseName("ix_recipes_shop_id");
        builder.HasIndex(r => r.ProductId).HasDatabaseName("ix_recipes_product_id");

        builder.Ignore(r => r.DomainEvents);
    }
}
