# Generated by Django 6.0.6 on 2026-07-17 10:29

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


def backfill_notice_period_ref(apps, schema_editor):
    """Link existing candidates to the Notice Period master by matching the
    legacy integer `notice_period` (days) to NoticePeriod.value."""
    Candidate = apps.get_model('candidates', 'Candidate')
    NoticePeriod = apps.get_model('master_data', 'NoticePeriod')
    by_value = {np.value: np for np in NoticePeriod.objects.all()}
    for cand in Candidate.objects.filter(notice_period__isnull=False, notice_period_ref__isnull=True):
        match = by_value.get(cand.notice_period)
        if match:
            cand.notice_period_ref = match
            cand.save(update_fields=['notice_period_ref'])


def noop_reverse(apps, schema_editor):
    pass


class Migration(migrations.Migration):

    dependencies = [
        ('candidates', '0009_emailoptout'),
        ('master_data', '0004_language'),
    ]

    operations = [
        migrations.AddField(
            model_name='candidate',
            name='notice_period_ref',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='candidates', to='master_data.noticeperiod'),
        ),
        migrations.RunPython(backfill_notice_period_ref, noop_reverse),
    ]
