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

namespace Lada.Framework.Data.Mappings.EntityMappings.Finances
{
    public class BankTransactionMap : IEntityMappingConfiguration<BankTransaction>
    {
        public void Map(EntityTypeBuilder<BankTransaction> builder)
        {
            builder.HasKey(t => t.Id);
            builder.Property(t => t.Id).ValueGeneratedOnAdd();

            // Properties
            builder.Property(t => t.TransactionCode)
                .HasMaxLength(128)
                .IsRequired();

            builder.Property(t => t.Description)
                .HasMaxLength(2048)
                .IsRequired();

            builder.Property(t => t.RawData)
                .HasMaxLength(4000);

            builder.Property(t => t.ReferenceNumber)
                .HasMaxLength(128);

            builder.Property(t => t.CounterpartyName)
                .HasMaxLength(512);

            builder.Property(t => t.CounterpartyAccount)
                .HasMaxLength(50);

            builder.Property(t => t.CounterpartyBank)
                .HasMaxLength(256);

            builder.Property(t => t.ProcessNote)
                .HasMaxLength(1024);

            // Decimal properties
            builder.Property(t => t.CreditAmount)
                .HasColumnType("decimal(18,2)")
                .HasDefaultValue(0);

            builder.Property(t => t.DebitAmount)
                .HasColumnType("decimal(18,2)")
                .HasDefaultValue(0);

            builder.Property(t => t.Balance)
                .HasColumnType("decimal(18,2)")
                .HasDefaultValue(0);

            // Indexes
            builder.HasIndex(t => t.BankAccountId)
                .HasDatabaseName("IX_BankTransaction_BankAccountId");

            builder.HasIndex(t => t.TransactionDate)
                .HasDatabaseName("IX_BankTransaction_TransactionDate");

            builder.HasIndex(t => new { t.BankAccountId, t.TransactionCode, t.TransactionDate })
                .HasDatabaseName("IX_BankTransaction_Account_Code_Date")
                .IsUnique();

            builder.HasIndex(t => t.ProcessStatus)
                .HasDatabaseName("IX_BankTransaction_ProcessStatus");

            builder.HasIndex(t => t.ImportId)
                .HasDatabaseName("IX_BankTransaction_ImportId");

            // Relationships
            builder.HasOne(t => t.BankAccount)
                .WithMany(a => a.BankTransactions)
                .HasForeignKey(t => t.BankAccountId)
                .OnDelete(DeleteBehavior.Cascade);

            builder.HasOne(t => t.BankStatementImport)
                .WithMany(i => i.BankTransactions)
                .HasForeignKey(t => t.ImportId)
                .OnDelete(DeleteBehavior.NoAction);

            builder.ToTable("BankTransaction");
        }
    }
}
