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

namespace ERPCore.Infra.Persistence.Configurations;

public sealed class BundleSaleConfiguration : IEntityTypeConfiguration<BundleSale>
{
    public void Configure(EntityTypeBuilder<BundleSale> builder)
    {
        builder.ToTable("bundle_sales");
        builder.HasKey(x => x.BundleSaleId);
        builder.Property(x => x.BundleNo).IsRequired().HasMaxLength(50);
        builder.HasIndex(x => x.BundleNo).IsUnique();
        builder.Property(x => x.BundleDate).IsRequired();
        builder.Property(x => x.CustomerSnapshotName).IsRequired().HasMaxLength(200);
        builder.Property(x => x.BundleName).IsRequired().HasMaxLength(200);
        builder.Property(x => x.BundleCode).IsRequired().HasMaxLength(50);
        builder.Property(x => x.Status)
            .HasConversion<string>().HasMaxLength(20).IsRequired()
            .HasDefaultValue(BundleSaleStatus.Draft);
        builder.Property(x => x.ComponentSubtotal).HasPrecision(18, 4);
        builder.Property(x => x.BundlePrice).HasPrecision(18, 4);
        builder.Property(x => x.MarginAmount).HasPrecision(18, 4);
        builder.Property(x => x.DiscountTotal).HasPrecision(18, 4);
        builder.Property(x => x.TaxTotal).HasPrecision(18, 4);
        builder.Property(x => x.GrandTotal).HasPrecision(18, 4);
        builder.Property(x => x.CreatedAt).IsRequired();
        builder.Property(x => x.ConcurrencyStamp)
            .IsRequired()
            .HasColumnType("integer")
            .HasDefaultValue(0)
            .IsConcurrencyToken();

        builder.HasOne(x => x.Customer).WithMany().HasForeignKey(x => x.CustomerId).OnDelete(DeleteBehavior.Restrict);
        builder.HasOne(x => x.Warehouse).WithMany().HasForeignKey(x => x.WarehouseId).OnDelete(DeleteBehavior.Restrict);
        builder.HasOne(x => x.CashierUser).WithMany().HasForeignKey(x => x.CashierUserId).OnDelete(DeleteBehavior.Restrict);
        builder.HasOne(x => x.BundleSaleTemplate).WithMany().HasForeignKey(x => x.BundleSaleTemplateId).OnDelete(DeleteBehavior.Restrict);

        builder.HasMany(x => x.Lines)
            .WithOne(x => x.BundleSale)
            .HasForeignKey(x => x.BundleSaleId)
            .OnDelete(DeleteBehavior.Cascade);
    }
}
