using Microsoft.EntityFrameworkCore;

using Monitoring.Core.Domain;
using Monitoring.Core.Domain.Primitives;

namespace Monitoring.Infrastructure.Data.Configurations;

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

		_ = builder.Property(x => x.Index)
			.IsRequired()
			.HasDefaultValue(new AreaIndex(0))
			.HasConversion(x => x.Value, x => new AreaIndex(x));

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

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

		_ = builder.HasOne(x => x.Asset)
			.WithMany(x => x.Areas)
			.HasForeignKey(x => x.AssetId)
			.IsRequired()
			.OnDelete(DeleteBehavior.Cascade);
		_ = builder.Property(x => x.AssetId)
			.HasConversion(x => x.Value, x => new(x));

		_ = builder.HasIndex(x => new
		{
			x.AssetId,
			x.Index,
		})
			.IsUnique();
	}
}
