# Generated by Django 3.2.24 on 2025-10-08 14:43

from django.db import (
    migrations,
)

from edu_rdm_integration.stages.utils import (
    update_foreign_key_constraint,
)


def apply_fk_updates(apps, schema_editor):
    """
    Применяет обновления внешних ключей для конкретных моделей.

    Здесь задаются таблицы и поведение при удалении записей,
    чтобы синхронизировать фактическое состояние БД с логикой моделей.
    """
    Entry = apps.get_model('uploader_client', 'Entry')
    RDMExportingDataSubStage = apps.get_model('edu_rdm_integration_export_data_stage', 'RDMExportingDataSubStage')
    RDMExportingDataSubStageAttachment = apps.get_model(
        'edu_rdm_integration_export_data_stage', 'RDMExportingDataSubStageAttachment'
    )
    RDMExportingDataSubStageUploaderClientLog = apps.get_model(
        'edu_rdm_integration_upload_data_stage', 'RDMExportingDataSubStageUploaderClientLog'
    )
    # Модель: RDMExportingDataSubStageUploaderClientLog
    # Поле sub_stage_id должно иметь ON DELETE CASCADE
    update_foreign_key_constraint(
        table_name=RDMExportingDataSubStageUploaderClientLog._meta.db_table,
        field_name="sub_stage_id",
        target_table=RDMExportingDataSubStage._meta.db_table,
        on_delete="CASCADE",
    )
    # Модель: RDMExportingDataSubStageUploaderClientLog
    # Поле attachment_id должно иметь ON DELETE CASCADE
    update_foreign_key_constraint(
        table_name=RDMExportingDataSubStageUploaderClientLog._meta.db_table,
        field_name="attachment_id",
        target_table=RDMExportingDataSubStageAttachment._meta.db_table,
        on_delete="CASCADE",
    )
    # Модель: RDMExportingDataSubStageUploaderClientLog
    # Поле entry_id должно иметь ON DELETE SET NULL
    update_foreign_key_constraint(
        table_name=RDMExportingDataSubStageUploaderClientLog._meta.db_table,
        field_name="entry_id",
        target_table=Entry._meta.db_table,
        on_delete="SET NULL",
    )

    RDMUploadStatusRequestLog = apps.get_model('edu_rdm_integration_upload_data_stage', 'RDMUploadStatusRequestLog')
    # Модель: RDMUploadStatusRequestLog
    # Поле upload_id должно иметь ON DELETE CASCADE
    update_foreign_key_constraint(
        table_name=RDMUploadStatusRequestLog._meta.db_table,
        field_name="upload_id",
        target_table=RDMExportingDataSubStageUploaderClientLog._meta.db_table,
        on_delete="CASCADE",
    )
    # Модель: RDMUploadStatusRequestLog
    # Поле entry_id должно иметь ON DELETE SET NULL
    update_foreign_key_constraint(
        table_name=RDMUploadStatusRequestLog._meta.db_table,
        field_name="entry_id",
        target_table=Entry._meta.db_table,
        on_delete="SET NULL",
    )


class Migration(migrations.Migration):

    dependencies = [
        ('edu_rdm_integration_upload_data_stage', '0003_auto_20251006_1417'),
    ]

    operations = [
        migrations.RunPython(apply_fk_updates, reverse_code=migrations.RunPython.noop),
    ]
