"""Add primary_answer FK to AnatomyQuestion and backfill existing values.

This migration adds a nullable FK `primary_answer` on AnatomyQuestion
pointing to Answer, then backfills it using the current logic of
selecting the first non-proposed CORRECT answer (status '2').
"""
from django.db import migrations, models
import django.db.models.deletion


def forwards(apps, schema_editor):
    AnatomyQuestion = apps.get_model('anatomy', 'AnatomyQuestion')
    Answer = apps.get_model('anatomy', 'Answer')

    # Select first non-proposed CORRECT answer (status '2') per question
    for q in AnatomyQuestion.objects.all():
        ans = Answer.objects.filter(question_id=q.pk, proposed=False, status='2').first()
        if ans:
            q.primary_answer_id = ans.pk
            q.save(update_fields=['primary_answer'])


def backwards(apps, schema_editor):
    AnatomyQuestion = apps.get_model('anatomy', 'AnatomyQuestion')
    for q in AnatomyQuestion.objects.all():
        q.primary_answer = None
        q.save(update_fields=['primary_answer'])


class Migration(migrations.Migration):

    dependencies = [
        ('anatomy', '0025_exam_created_exam_updated'),
    ]

    operations = [
        migrations.AddField(
            model_name='anatomyquestion',
            name='primary_answer',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='primary_for_questions', to='anatomy.answer'),
        ),
        migrations.RunPython(forwards, backwards),
    ]
