using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using TeleWave.Domain.Broadcast;

namespace TeleWave.Infrastructure.Persistence.Configurations;

public class ChannelConfiguration : IEntityTypeConfiguration<Channel>
{
    public void Configure(EntityTypeBuilder<Channel> builder)
    {
        builder.Property(x => x.Name).IsRequired().HasMaxLength(256);
        builder.Property(x => x.Slug).IsRequired().HasMaxLength(128);
        builder.HasIndex(x => x.Slug).IsUnique();

        // Номер канала уникален среди заданных: переключение вверх-вниз по номерам иначе неоднозначно.
        builder.HasIndex(x => x.Number).IsUnique().HasFilter("\"Number\" IS NOT NULL");

        builder
            .HasMany(x => x.BumperTemplates)
            .WithOne()
            .HasForeignKey(t => t.ChannelId)
            .OnDelete(DeleteBehavior.Cascade);
        builder.Navigation(x => x.BumperTemplates).UsePropertyAccessMode(PropertyAccessMode.Field);
    }
}

public class BumperTemplateConfiguration : IEntityTypeConfiguration<BumperTemplate>
{
    public void Configure(EntityTypeBuilder<BumperTemplate> builder)
    {
        builder.HasIndex(x => new { x.ChannelId, x.Position });
        builder.Property(x => x.Name).IsRequired().HasMaxLength(64);
        builder.Property(x => x.BackgroundColor).IsRequired().HasMaxLength(32);
        builder.Property(x => x.BackgroundColor2).IsRequired().HasMaxLength(32);
        builder.Property(x => x.AccentColor).IsRequired().HasMaxLength(32);
        builder.Property(x => x.TextColor).IsRequired().HasMaxLength(32);
        builder.Property(x => x.AudioExtension).HasMaxLength(16);

        builder
            .HasMany(x => x.Variants)
            .WithOne()
            .HasForeignKey(v => v.BumperTemplateId)
            .OnDelete(DeleteBehavior.Cascade);
        builder.Navigation(x => x.Variants).UsePropertyAccessMode(PropertyAccessMode.Field);
    }
}

public class BumperTextVariantConfiguration : IEntityTypeConfiguration<BumperTextVariant>
{
    public void Configure(EntityTypeBuilder<BumperTextVariant> builder)
    {
        builder.HasIndex(x => new { x.BumperTemplateId, x.Position });
        builder.Property(x => x.Name).IsRequired().HasMaxLength(64);
        builder.Property(x => x.NowLabel).IsRequired().HasMaxLength(64);
        builder.Property(x => x.NextLabel).IsRequired().HasMaxLength(64);
        builder.Property(x => x.Line1).IsRequired().HasMaxLength(120);
        builder.Property(x => x.Line2).IsRequired().HasMaxLength(120);
        builder.Property(x => x.Weight).HasDefaultValue(BumperTextVariant.DefaultWeight);
    }
}
