using Microsoft.EntityFrameworkCore;

using Monitoring.Core.Domain.AssetGroupManagement;

namespace Monitoring.Infrastructure.Data.Configurations;

public class AssetGroupConfiguration : IEntityTypeConfiguration<AssetGroup>
{
	public void Configure(Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder<AssetGroup> builder)
	{
		_ = builder.HasKey(x => x.Id);
		_ = builder.Property(x => x.Id)
			.IsRequired()
			.HasConversion(x => x.Value, x => new(x));

		_ = builder.Property(x => x.Name)
			.IsRequired()
			.HasMaxLength(AssetGroupName.MaxLength)
			.HasConversion(x => x.Value, x => AssetGroupName.Create(x));

		_ = builder.HasOne(x => x.Organization)
			.WithMany(x => x.AssetGroups)
			.HasForeignKey(x => x.OrganizationId)
			.OnDelete(DeleteBehavior.Cascade);
		_ = builder.Property(x => x.OrganizationId)
			.HasConversion(x => x.Value, x => new(x));

		_ = builder.HasOne(x => x.Parent)
			.WithMany(x => x.Children)
			.HasForeignKey(x => x.ParentId)
			.OnDelete(DeleteBehavior.SetNull);
		_ = builder.Property(x => x.ParentId)
			.HasConversion(x => x!.Value, x => new(x));
	}
}
