using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

using Monitoring.Core.Domain.UserSettingsManagement;
using Monitoring.Core.Domain.AssetGroupManagement;
using Monitoring.Core.Domain.UserPrimitives;

namespace Monitoring.Infrastructure.Data.Configurations;

public class UserSettingsConfiguration : IEntityTypeConfiguration<UserSettings>
{
    public void Configure(EntityTypeBuilder<UserSettings> builder)
    {
        builder.HasKey(x => x.Id);
        
        builder.Property(x => x.Id)
            .HasConversion(
                id => id.Value,
                value => UserSettingsId.Create(value));

        builder.Property(x => x.UserId)
            .HasConversion(
                id => id.Value,
                value => new UserId(value));

        builder.Property(x => x.PositioningStrategy)
            .HasConversion(
                strategy => strategy.Value,
                value => PositioningStrategy.Create(value))
            .IsRequired();

        builder.OwnsOne(x => x.ManualPosition, manualPosition =>
        {
            manualPosition.Property(p => p.Latitude).HasColumnName("ManualLatitude");
            manualPosition.Property(p => p.Longitude).HasColumnName("ManualLongitude");
        });

        builder.Property(x => x.AssetGroupId)
            .HasConversion(
                id => id!.Value,
                value => new AssetGroupId(value));

        builder.Property(x => x.CreatedAt)
            .IsRequired();

        builder.Property(x => x.UpdatedAt)
            .IsRequired();

        // Уникальный индекс по UserId
        builder.HasIndex(x => x.UserId)
            .IsUnique();

        // Связь с пользователем
        builder.HasOne<Core.Domain.User>()
            .WithOne()
            .HasForeignKey<UserSettings>(x => x.UserId)
            .OnDelete(DeleteBehavior.Cascade);
    }
} 