# Generated by Django 4.2.29 on 2026-03-03 22:48

# Django
import django.db.models.deletion
from django.db import migrations, models


def _on_migrate(apps, schema_editor):
    """
    Data migration to populate the 'ship' field in the SrpRequest model based on the existing 'ship_type_id' field.
    This function will be called during the migration process to ensure that existing data is preserved and correctly linked.
    """

    srp_request_model = apps.get_model("aasrp", "SrpRequest")
    item_type_model = apps.get_model("eve_sde", "ItemType")
    db_alias = schema_editor.connection.alias
    srp_requests = srp_request_model.objects.using(db_alias).all()
    tmp_item_type_cache = {}

    print("\n\nStarting data migration for SDE ItemType relationships…")
    print(f"Total SrpRequest records to process: {srp_requests.count()}")

    for srp_request in srp_requests:
        if srp_request.ship_type_id:
            try:
                if srp_request.ship_type_id not in tmp_item_type_cache:
                    item_type = item_type_model.objects.using(db_alias).get(
                        pk=srp_request.ship_type_id
                    )
                    tmp_item_type_cache[srp_request.ship_type_id] = item_type

                srp_request.ship = tmp_item_type_cache[srp_request.ship_type_id]
                srp_request.save()
            except item_type_model.DoesNotExist:
                # If the ItemType does not exist, we can choose to log this or simply skip it
                pass

    print("Data migration completed.\n\n")


class Migration(migrations.Migration):

    dependencies = [
        ("eve_sde", "0014_dogmaeffect_description_de_and_more"),
        ("aasrp", "0001_init"),
    ]

    operations = [
        migrations.RenameField(
            model_name="srprequest",
            old_name="ship_id",
            new_name="ship_type_id",
        ),
        migrations.AddField(
            model_name="srprequest",
            name="ship",
            field=models.ForeignKey(
                blank=True,
                default=None,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="srp_requests",
                to="eve_sde.itemtype",
                verbose_name="Ship",
            ),
        ),
        migrations.RunPython(
            code=_on_migrate,
            reverse_code=migrations.RunPython.noop,
        ),
        migrations.RemoveField(
            model_name="srprequest",
            name="ship_name",
        ),
        migrations.RemoveField(
            model_name="srprequest",
            name="ship_type_id",
        ),
    ]
