# Generated by Django 4.2.16 on 2024-11-01 10:58
import logging

from django.db import migrations

logger = logging.getLogger(__name__)


def populate_slack_channel(apps, schema_editor):
    SlackMessage = apps.get_model("slack", "SlackMessage")
    SlackChannel = apps.get_model("slack", "SlackChannel")

    logger.info("Starting migration to populate the 'channel' field.")

    # Filter SlackMessages that need to be updated
    slack_messages = SlackMessage.objects.filter(
        _channel_id__isnull=False,  # Old column
        organization_id__isnull=False,
        channel_id__isnull=True,  # New column to be populated
    )

    total_messages = slack_messages.count()
    if total_messages == 0:
        logger.info("No SlackMessages need updating.")
        return

    logger.info(f"Found {total_messages} SlackMessages to update.")

    updated_count = 0

    # Use iterator() to avoid loading all records into memory at once
    for message in slack_messages.iterator():
        try:
            slack_team_identity = message.organization.slack_team_identity

            channel = SlackChannel.objects.filter(
                slack_id=message._channel_id,
                slack_team_identity=slack_team_identity,
            ).first()

            if channel:
                message.channel = channel
                message.save(update_fields=["channel"])
                updated_count += 1
            else:
                logger.warning(
                    f"No SlackChannel found for SlackMessage id {message.id} "
                    f"with slack_id {message._channel_id} and "
                    f"slack_team_identity_id {slack_team_identity.id}."
                )
        except Exception as e:
            logger.error(f"Error updating SlackMessage id {message.id}: {e}")

    logger.info(f"Updated {updated_count} SlackMessages.")
    logger.info("Finished migration to populate the 'channel' field.")


class Migration(migrations.Migration):
    dependencies = [
        ("slack", "0006_rename_channel_id_slackmessage__channel_id_and_more"),
    ]

    operations = [
        migrations.RunPython(populate_slack_channel, migrations.RunPython.noop),
    ]
