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 ReconciliationMap : IEntityMappingConfiguration<Reconciliation>
    {
        public void Map(EntityTypeBuilder<Reconciliation> builder)
        {
            builder.ToTable("Reconciliations");

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

            // Properties
            builder.Property(x => x.Code)
                .HasMaxLength(64)
                .IsRequired();

            builder.Property(x => x.CreatedByUserName)
                .HasMaxLength(128)
                .IsRequired();

            builder.Property(x => x.ApprovedByUsername)
                .HasMaxLength(128);

            builder.Property(x => x.TransferredByUsername)
                .HasMaxLength(128);

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

            builder.Property(x => x.BankAccountNumber)
                .HasMaxLength(64);

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

            builder.Property(x => x.BankCode)
                .HasMaxLength(16);

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

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

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

            builder.Property(x => x.TransferInfo)
                .HasMaxLength(1024);

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

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

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

            // Relationships
            builder.HasOne(x => x.Customer)
                .WithMany()
                .HasForeignKey(x => x.CustomerId)
                .OnDelete(DeleteBehavior.Restrict);

            builder.HasMany(x => x.Orders)
                .WithOne(x => x.Reconciliation)
                .HasForeignKey(x => x.ReconciliationId)
                .OnDelete(DeleteBehavior.Cascade);

            builder.HasOne(x => x.Transaction)
                .WithMany()
                .HasForeignKey(x => x.TransactionId)
                .OnDelete(DeleteBehavior.SetNull);

            // Indexes
            builder.HasIndex(x => x.Code)
                .IsUnique();

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

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

            builder.HasIndex(x => new { x.FromDate, x.ToDate });

            builder.HasIndex(x => x.CreatedTime);
        }
    }
}
