using Lada.Framework.Data.Domains.Finance;
using Lada.Framework.Data.Mappings;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Lada.Framework.Data.Mappings.EntityMappings.Finance
{
    public class ReconciliationOrderMap : IEntityMappingConfiguration<ReconciliationOrder>
    {
        public void Map(EntityTypeBuilder<ReconciliationOrder> builder)
        {
            builder.ToTable("ReconciliationOrders");

            // Primary Key
            builder.HasKey(x => x.Id);

            // Properties
            builder.Property(x => x.OrderCode)
                .HasMaxLength(128)
                .IsRequired();

            builder.Property(x => x.PartnerCode)
                .HasMaxLength(256);

            builder.Property(x => x.Note)
                .HasMaxLength(512);

            builder.Property(x => x.DeliveryAddress)
                .HasMaxLength(512);

            builder.Property(x => x.ReceiverName)
                .HasMaxLength(256);

            builder.Property(x => x.ReceiverPhone)
                .HasMaxLength(32);

            // Decimal precision
            builder.Property(x => x.CodAmount)
                .HasPrecision(18, 2);

            builder.Property(x => x.FeeAmount)
                .HasPrecision(18, 2);

            builder.Property(x => x.NetAmount)
                .HasPrecision(18, 2);

            builder.Property(x => x.ChargeWeight)
                .HasPrecision(18, 3);

            builder.Property(x => x.ShippingFee)
                .HasPrecision(18, 2);

            // Relationships
            builder.HasOne(x => x.Reconciliation)
                .WithMany(x => x.Orders)
                .HasForeignKey(x => x.ReconciliationId)
                .OnDelete(DeleteBehavior.Cascade);

            builder.HasOne(x => x.Order)
                .WithMany()
                .HasForeignKey(x => x.OrderId)
                .OnDelete(DeleteBehavior.Restrict);

            // Indexes
            builder.HasIndex(x => x.ReconciliationId);

            builder.HasIndex(x => x.OrderId);

            builder.HasIndex(x => x.OrderCode);

            builder.HasIndex(x => new { x.ReconciliationId, x.OrderId })
                .IsUnique();
        }
    }
}
