# Generated by Django 5.1.15 on 2026-02-05 14:36

from django.db import migrations, models

def backfill_outbox_fields(apps, schema_editor):
    """Backfill has_delivery_pending, has_delivery_failed
    for threads that have recipients with pending/failed delivery status."""
    Thread = apps.get_model("core", "Thread")
    MessageRecipient = apps.get_model("core", "MessageRecipient")

    # These values match MessageDeliveryStatusChoices from core/enums.py
    DELIVERY_STATUS_FAILED = 3
    DELIVERY_STATUS_RETRY = 4

    # Base filter for sender messages that are not drafts or trashed
    base_recipient_filter = models.Q(
        message__is_sender=True,
        message__is_draft=False,
        message__is_trashed=False,
    )

    # Subquery to check if thread has any failed delivery
    has_failed_subquery = MessageRecipient.objects.filter(
        base_recipient_filter,
        message__thread=models.OuterRef("pk"),
        delivery_status=DELIVERY_STATUS_FAILED,
    )

    # Subquery to check if thread has any pending delivery
    # (sending=None, retrying, or failed)
    has_pending_subquery = MessageRecipient.objects.filter(
        base_recipient_filter,
        message__thread=models.OuterRef("pk"),
    ).filter(
        models.Q(delivery_status__isnull=True)
        | models.Q(delivery_status__in=[DELIVERY_STATUS_FAILED, DELIVERY_STATUS_RETRY])
    )

    # Update threads with failed deliveries in bulk
    Thread.objects.filter(
        models.Exists(has_failed_subquery)
    ).update(has_delivery_failed=True)

    # Update threads with pending deliveries in bulk
    Thread.objects.filter(
        models.Exists(has_pending_subquery)
    ).update(has_delivery_pending=True)

class Migration(migrations.Migration):

    dependencies = [
        ('core', '0015_attachment_cid'),
    ]

    operations = [
        migrations.AddField(
            model_name='thread',
            name='has_delivery_failed',
            field=models.BooleanField(default=False, help_text='True if thread has messages with permanent delivery failure.', verbose_name='has delivery failed'),
        ),
        migrations.AddField(
            model_name='thread',
            name='has_delivery_pending',
            field=models.BooleanField(default=False, help_text='True if thread has messages awaiting successful delivery (sending, retrying, or failed).', verbose_name='has delivery pending'),
        ),
        migrations.AlterField(
            model_name='messagerecipient',
            name='delivery_status',
            field=models.SmallIntegerField(blank=True, choices=[(1, 'internal'), (2, 'sent'), (3, 'failed'), (4, 'retry'), (5, 'cancelled')], null=True, verbose_name='delivery status'),
        ),
        migrations.RunPython(backfill_outbox_fields, migrations.RunPython.noop),
    ]
