using foodmarket.Domain.Inventory;
using Microsoft.EntityFrameworkCore;

namespace foodmarket.Infrastructure.Persistence.Configurations;

public static class InventoryConfigurations
{
    public static void ConfigureInventory(this ModelBuilder b)
    {
        b.Entity<Stock>(e =>
        {
            e.ToTable("stocks");
            e.Property(x => x.Quantity).HasPrecision(18, 4);
            e.Property(x => x.ReservedQuantity).HasPrecision(18, 4);
            e.Ignore(x => x.Available);

            e.HasOne(x => x.Product).WithMany().HasForeignKey(x => x.ProductId).OnDelete(DeleteBehavior.Cascade);
            e.HasOne(x => x.Store).WithMany().HasForeignKey(x => x.StoreId).OnDelete(DeleteBehavior.Cascade);

            e.HasIndex(x => new { x.OrganizationId, x.ProductId, x.StoreId }).IsUnique();
            e.HasIndex(x => new { x.OrganizationId, x.StoreId });
        });

        b.Entity<StockMovement>(e =>
        {
            e.ToTable("stock_movements");
            e.Property(x => x.Quantity).HasPrecision(18, 4);
            e.Property(x => x.UnitCost).HasPrecision(18, 4);
            e.Property(x => x.DocumentType).HasMaxLength(50).IsRequired();
            e.Property(x => x.DocumentNumber).HasMaxLength(50);
            e.Property(x => x.Notes).HasMaxLength(500);

            e.HasOne(x => x.Product).WithMany().HasForeignKey(x => x.ProductId).OnDelete(DeleteBehavior.Restrict);
            e.HasOne(x => x.Store).WithMany().HasForeignKey(x => x.StoreId).OnDelete(DeleteBehavior.Restrict);

            e.HasIndex(x => new { x.OrganizationId, x.ProductId, x.OccurredAt });
            e.HasIndex(x => new { x.OrganizationId, x.StoreId, x.OccurredAt });
            e.HasIndex(x => new { x.DocumentType, x.DocumentId });
        });
    }
}
