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

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

public class FuelCardMap : IEntityMappingConfiguration<FuelCard>
{
    public void Map(EntityTypeBuilder<FuelCard> builder)
    {
        builder.ToTable("FuelCards");

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

        // Properties
        builder.Property(x => x.CardNumber)
            .IsRequired()
            .HasMaxLength(50);

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

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

        builder.Property(x => x.CardType)
            .HasMaxLength(50)
            .HasDefaultValue(string.Empty);

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

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

        builder.Property(x => x.CurrentDebt)
            .HasPrecision(18, 2)
            .HasDefaultValue(0);

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

        // Relationships
        builder.HasOne(x => x.ResponsibleUser)
            .WithMany()
            .HasForeignKey(x => x.ResponsibleUserId)
            .OnDelete(DeleteBehavior.SetNull);

        builder.HasMany(x => x.FuelCardTransactions)
            .WithOne(x => x.FuelCard)
            .HasForeignKey(x => x.FuelCardId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasMany(x => x.FuelCardStatementImports)
            .WithOne(x => x.FuelCard)
            .HasForeignKey(x => x.FuelCardId)
            .OnDelete(DeleteBehavior.Restrict);

        // Indexes
        builder.HasIndex(x => x.CardNumber)
            .IsUnique()
            .HasDatabaseName("IX_FuelCards_CardNumber");

        builder.HasIndex(x => x.ResponsibleUserId)
            .HasDatabaseName("IX_FuelCards_ResponsibleUserId");

        builder.HasIndex(x => x.Status)
            .HasDatabaseName("IX_FuelCards_Status");
    }
}
