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

namespace Lada.Framework.Data.Mappings.EntityMappings.Finance;

public class FuelCardStatementImportMap : IEntityMappingConfiguration<FuelCardStatementImport>
{
    public void Map(EntityTypeBuilder<FuelCardStatementImport> builder)
    {
        builder.ToTable("FuelCardStatementImports");

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

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

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

        builder.Property(x => x.FilePath)
            .HasMaxLength(1024)
            .HasDefaultValue(string.Empty);

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

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

        builder.Property(x => x.ErrorMessage)
            .HasMaxLength(2048)
            .HasDefaultValue(string.Empty);

        builder.Property(x => x.ImportedByUserName)
            .HasMaxLength(256)
            .HasDefaultValue(string.Empty);

        // Relationships
        builder.HasOne(x => x.FuelCard)
            .WithMany(x => x.FuelCardStatementImports)
            .HasForeignKey(x => x.FuelCardId)
            .OnDelete(DeleteBehavior.Restrict);

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

        builder.HasMany(x => x.FuelCardTransactions)
            .WithOne(x => x.FuelCardStatementImport)
            .HasForeignKey(x => x.ImportId)
            .OnDelete(DeleteBehavior.SetNull);

        // Indexes
        builder.HasIndex(x => x.FuelCardId)
            .HasDatabaseName("IX_FuelCardStatementImports_FuelCardId");

        builder.HasIndex(x => x.ImportedByUserId)
            .HasDatabaseName("IX_FuelCardStatementImports_ImportedByUserId");

        builder.HasIndex(x => x.ImportStatus)
            .HasDatabaseName("IX_FuelCardStatementImports_ImportStatus");

        builder.HasIndex(x => new { x.StatementPeriodFrom, x.StatementPeriodTo })
            .HasDatabaseName("IX_FuelCardStatementImports_Period");
    }
}
