using Microsoft.EntityFrameworkCore;

using Monitoring.Core.Domain.TokenManagement;

namespace Monitoring.Infrastructure.Data.Configurations;

public class TokenConfiguration : IEntityTypeConfiguration<Token>
{
	public void Configure(Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder<Token> 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(TokenName.MaxLength)
			.HasConversion(x => x.Value, x => TokenName.Create(x));

		_ = builder.Property(x => x.Code)
			.IsRequired()
			.HasMaxLength(TokenCode.MaxLength)
			.HasConversion(x => x!.Value, x => TokenCode.Create(x));

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