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

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

            // Properties
            builder.Property(i => i.OriginalFileName)
                .HasMaxLength(512)
                .IsRequired();

            builder.Property(i => i.FilePath)
                .HasMaxLength(1024)
                .IsRequired();

            builder.Property(i => i.ErrorMessage)
                .HasMaxLength(2048);

            builder.Property(i => i.ImportedByUserName)
                .HasMaxLength(256)
                .IsRequired();

            // Default values
            builder.Property(i => i.TotalRows)
                .HasDefaultValue(0);

            builder.Property(i => i.ProcessedRows)
                .HasDefaultValue(0);

            builder.Property(i => i.ErrorRows)
                .HasDefaultValue(0);

            builder.Property(i => i.SkippedRows)
                .HasDefaultValue(0);

            builder.Property(i => i.DuplicateRows)
                .HasDefaultValue(0);

            builder.Property(i => i.OverwriteExisting)
                .HasDefaultValue(false);

            // Indexes
            builder.HasIndex(i => i.BankAccountId)
                .HasDatabaseName("IX_BankStatementImport_BankAccountId");

            builder.HasIndex(i => i.ImportStatus)
                .HasDatabaseName("IX_BankStatementImport_ImportStatus");

            builder.HasIndex(i => i.CreatedTime)
                .HasDatabaseName("IX_BankStatementImport_CreatedTime");

            builder.HasIndex(i => i.ImportedByUserId)
                .HasDatabaseName("IX_BankStatementImport_ImportedByUserId");

            builder.HasIndex(i => new { i.BankAccountId, i.CreatedTime })
                .HasDatabaseName("IX_BankStatementImport_Account_Created");

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

            builder.HasOne(i => i.ImportedByUser)
                .WithMany()
                .HasForeignKey(i => i.ImportedByUserId)
                .OnDelete(DeleteBehavior.Restrict);

            builder.HasMany(i => i.BankTransactions)
                .WithOne(t => t.BankStatementImport)
                .HasForeignKey(t => t.ImportId)
                .OnDelete(DeleteBehavior.SetNull);

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