using ERPCore.Domain.Entities;
using ERPCore.Domain.Enums;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace ERPCore.Infra.Persistence.Configurations;

public sealed class CustomerConfiguration : IEntityTypeConfiguration<Customer>
{
    public void Configure(EntityTypeBuilder<Customer> builder)
    {
        builder.ToTable("customers");
        builder.HasKey(c => c.CustomerId);

        builder.Property(c => c.CustomerCode).IsRequired().HasMaxLength(50);
        builder.HasIndex(c => c.CustomerCode).IsUnique();

        builder.Property(c => c.CustomerType)
            .HasConversion<string>().HasMaxLength(20).IsRequired()
            .HasDefaultValue(CustomerType.B2C);

        builder.Property(c => c.Name).IsRequired().HasMaxLength(200);
        builder.Property(c => c.DisplayName).HasMaxLength(200);
        builder.Property(c => c.Phone).HasMaxLength(30);
        builder.Property(c => c.Email).HasMaxLength(100);
        builder.Property(c => c.AddressLine1).HasMaxLength(250);
        builder.Property(c => c.AddressLine2).HasMaxLength(250);
        builder.Property(c => c.City).HasMaxLength(100);
        builder.Property(c => c.Country).HasMaxLength(100);
        builder.Property(c => c.TaxRegistrationNo).HasMaxLength(50);

        builder.Property(c => c.CreditLimit).HasPrecision(18, 4);
        builder.Property(c => c.CreditDays).IsRequired();

        builder.HasOne(c => c.DefaultWarehouse)
            .WithMany()
            .HasForeignKey(c => c.DefaultWarehouseId)
            .OnDelete(DeleteBehavior.SetNull);

        builder.Property(c => c.Status)
            .HasConversion<string>().HasMaxLength(20).IsRequired()
            .HasDefaultValue(EntityStatus.Active);

        builder.Property(c => c.CreatedAt).IsRequired();
        builder.Property(c => c.RowVersion).IsRowVersion();

        builder.HasIndex(c => c.Status);
        builder.HasIndex(c => c.CustomerType);
    }
}
