using Microsoft.EntityFrameworkCore;

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

namespace Monitoring.Infrastructure.Data.Configurations;

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

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

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

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

		_ = builder.HasOne(x => x.Area)
			.WithMany(x => x.Zones)
			.HasForeignKey(x => x.AreaId)
			.OnDelete(DeleteBehavior.Cascade);
		_ = builder.Property(x => x.AreaId)
			.HasConversion(x => x.Value, x => new(x));

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