# Generated manually to migrate subject data from CharField to ForeignKey

from django.db import migrations, connection


def migrate_subject_data_forward(apps, schema_editor):
    """
    Перенос данных из старого поля subject (CharField) в subject_name.
    Выполняется перед изменением типа поля subject на ForeignKey.
    """
    # Проверяем тип колонки subject в базе данных
    with connection.cursor() as cursor:
        # Для таблицы lessons
        cursor.execute("""
            SELECT data_type 
            FROM information_schema.columns 
            WHERE table_name = 'lessons' AND column_name = 'subject'
        """)
        result = cursor.fetchone()
        
        if result and result[0] == 'character varying':  # CharField в PostgreSQL
            # Переносим данные из subject в subject_name для Lesson
            cursor.execute("""
                UPDATE lessons 
                SET subject_name = subject 
                WHERE subject IS NOT NULL 
                AND subject != '' 
                AND (subject_name IS NULL OR subject_name = '')
            """)
        
        # Для таблицы lesson_templates
        cursor.execute("""
            SELECT data_type 
            FROM information_schema.columns 
            WHERE table_name = 'lesson_templates' AND column_name = 'subject'
        """)
        result = cursor.fetchone()
        
        if result and result[0] == 'character varying':  # CharField в PostgreSQL
            # Переносим данные из subject в subject_name для LessonTemplate
            cursor.execute("""
                UPDATE lesson_templates 
                SET subject_name = subject 
                WHERE subject IS NOT NULL 
                AND subject != '' 
                AND (subject_name IS NULL OR subject_name = '')
            """)


def migrate_subject_data_backward(apps, schema_editor):
    """
    Обратная миграция - перенос данных из subject_name обратно в subject.
    """
    Lesson = apps.get_model('schedule', 'Lesson')
    LessonTemplate = apps.get_model('schedule', 'LessonTemplate')
    
    # Переносим данные из subject_name обратно в subject для Lesson
    for lesson in Lesson.objects.all():
        if lesson.subject_name:
            lesson.subject = lesson.subject_name
            lesson.save(update_fields=['subject'])
    
    # Переносим данные из subject_name обратно в subject для LessonTemplate
    for template in LessonTemplate.objects.all():
        if template.subject_name:
            template.subject = template.subject_name
            template.save(update_fields=['subject'])


class Migration(migrations.Migration):
    dependencies = [
        ('schedule', '0005_lesson_subject_name_lessontemplate_subject_name_and_more'),
    ]

    operations = [
        migrations.RunPython(
            migrate_subject_data_forward,
            migrate_subject_data_backward,
        ),
    ]
