# Generated by Django 3.2.24 on 2025-10-17 14:15

from django.db import (
    migrations,
)

from edu_rdm_integration.stages.utils import (
    update_foreign_key_constraint,
)


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

    Здесь задаются таблицы и поведение при удалении записей,
    чтобы синхронизировать фактическое состояние БД с логикой моделей.
    """
    RDMExportingDataSubStage = apps.get_model('edu_rdm_integration_export_data_stage', 'RDMExportingDataSubStage')
    RDMExportingDataStage = apps.get_model('edu_rdm_integration_export_data_stage', 'RDMExportingDataStage')

    RDMExportingDataSubStageAttachment = apps.get_model(
        'edu_rdm_integration_export_data_stage', 'RDMExportingDataSubStageAttachment'
    )
    # Модель: RDMExportingDataSubStageAttachment
    # Поле exporting_data_sub_stage_id должно иметь ON DELETE CASCADE
    update_foreign_key_constraint(
        table_name=RDMExportingDataSubStageAttachment._meta.db_table,
        field_name='exporting_data_sub_stage_id',
        target_table=RDMExportingDataSubStage._meta.db_table,
        on_delete='SET NULL',
    )

    RDMExportingDataSubStageEntity = apps.get_model(
        'edu_rdm_integration_export_data_stage', 'RDMExportingDataSubStageEntity'
    )
    # Модель: CollectDataCommandProgress
    # Поле exporting_data_sub_stage_id должно иметь ON DELETE CASCADE
    update_foreign_key_constraint(
        table_name=RDMExportingDataSubStageEntity._meta.db_table,
        field_name='exporting_data_sub_stage_id',
        target_table=RDMExportingDataSubStage._meta.db_table,
        on_delete='CASCADE',
    )

    RDMExportingDataCommandProgress = apps.get_model(
        'edu_rdm_integration_export_data_stage', 'RDMExportingDataCommandProgress'
    )
    # Модель: RDMExportingDataCommandProgress
    # Поле stage_id должно иметь ON DELETE SET NULL
    update_foreign_key_constraint(
        table_name=RDMExportingDataCommandProgress._meta.db_table,
        field_name='stage_id',
        target_table=RDMExportingDataStage._meta.db_table,
        on_delete='SET NULL',
    )

    # Таблица: rdm_exporting_data_command_progress
    # Поле stage_id должно иметь ON DELETE SET NULL
    update_foreign_key_constraint(
        table_name='rdm_exporting_data_command_progress',
        field_name="stage_id",
        target_table=RDMExportingDataStage._meta.db_table,
        on_delete="SET NULL",
    )


class Migration(migrations.Migration):

    dependencies = [
        ('edu_rdm_integration_export_data_stage', '0003_alter_rdmexportingdatasubstageattachment_exporting_data_sub_stage'),
    ]

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