using foodmarket.Domain.Purchases;
using Microsoft.EntityFrameworkCore;

namespace foodmarket.Infrastructure.Persistence.Configurations;

public static class PurchasesConfigurations
{
    public static void ConfigurePurchases(this ModelBuilder b)
    {
        b.Entity<Supply>(e =>
        {
            e.ToTable("supplies");
            e.Property(x => x.Number).HasMaxLength(50).IsRequired();
            e.Property(x => x.Notes).HasMaxLength(1000);
            e.Property(x => x.Total).HasPrecision(18, 4);

            e.HasOne(x => x.Supplier).WithMany().HasForeignKey(x => x.SupplierId).OnDelete(DeleteBehavior.Restrict);
            e.HasOne(x => x.Store).WithMany().HasForeignKey(x => x.StoreId).OnDelete(DeleteBehavior.Restrict);
            e.HasOne(x => x.Currency).WithMany().HasForeignKey(x => x.CurrencyId).OnDelete(DeleteBehavior.Restrict);

            e.HasMany(x => x.Lines).WithOne(l => l.Supply).HasForeignKey(l => l.SupplyId).OnDelete(DeleteBehavior.Cascade);

            e.HasIndex(x => new { x.OrganizationId, x.Number }).IsUnique();
            e.HasIndex(x => new { x.OrganizationId, x.Date });
            e.HasIndex(x => new { x.OrganizationId, x.Status });
            e.HasIndex(x => new { x.OrganizationId, x.SupplierId });
        });

        b.Entity<SupplyLine>(e =>
        {
            e.ToTable("supply_lines");
            e.Property(x => x.Quantity).HasPrecision(18, 4);
            e.Property(x => x.UnitPrice).HasPrecision(18, 4);
            e.Property(x => x.LineTotal).HasPrecision(18, 4);

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

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