# Generated by Django 5.1.6 on 2025-04-18 16:21

from django.db import migrations, models
from django.db.models import Count

def remove_duplicate_channel_streams(apps, schema_editor):
    ChannelStream = apps.get_model('dispatcharr_channels', 'ChannelStream')
    # Find duplicates by (channel, stream)
    duplicates = (
        ChannelStream.objects
        .values('channel', 'stream')
        .annotate(count=Count('id'))
        .filter(count__gt=1)
    )

    for dupe in duplicates:
        # Get all duplicates for this pair
        dups = ChannelStream.objects.filter(
            channel=dupe['channel'],
            stream=dupe['stream']
        ).order_by('id')

        # Keep the first one, delete the rest
        dups.exclude(id=dups.first().id).delete()

class Migration(migrations.Migration):

    dependencies = [
        ('dispatcharr_channels', '0015_recording_custom_properties'),
    ]

    operations = [
        migrations.RunPython(remove_duplicate_channel_streams),
        migrations.AddConstraint(
            model_name='channelstream',
            constraint=models.UniqueConstraint(fields=('channel', 'stream'), name='unique_channel_stream'),
        ),
    ]
