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

namespace Lada.Framework.Data.Mappings.EntityMappings.Finance
{
    public class UserBankAccountMap : IEntityTypeConfiguration<UserBankAccount>
    {
        public void Configure(EntityTypeBuilder<UserBankAccount> builder)
        {
            builder.ToTable("UserBankAccounts");

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

            // Properties
            builder.Property(x => x.UserId)
                .IsRequired();

            builder.Property(x => x.AccountNumber)
                .IsRequired()
                .HasMaxLength(64);

            builder.Property(x => x.AccountHolderName)
                .IsRequired()
                .HasMaxLength(256);

            builder.Property(x => x.BankId)
                .IsRequired();

            builder.Property(x => x.IsDefault)
                .IsRequired()
                .HasDefaultValue(false);

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

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

            builder.HasOne(x => x.Bank)
                .WithMany()
                .HasForeignKey(x => x.BankId)
                .OnDelete(DeleteBehavior.Restrict);

            builder.HasMany(x => x.Expenses)
                .WithOne(x => x.UserBankAccount)
                .HasForeignKey(x => x.UserBankAccountId)
                .OnDelete(DeleteBehavior.SetNull);

            // Indexes
            builder.HasIndex(x => x.UserId)
                .HasDatabaseName("IX_UserBankAccounts_UserId");

            builder.HasIndex(x => x.BankId)
                .HasDatabaseName("IX_UserBankAccounts_BankId");

            builder.HasIndex(x => new { x.UserId, x.IsDefault })
                .HasDatabaseName("IX_UserBankAccounts_UserId_IsDefault");

            builder.HasIndex(x => x.AccountNumber)
                .HasDatabaseName("IX_UserBankAccounts_AccountNumber");
        }
    }
}
