# Generated by Django 5.2.13 on 2026-05-05 08:51

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


def _backfill_status(apps, schema_editor):
    """Set existing scholars to COMPLETED if they have a graduation, else ACTIVE.

    The model's default is ENROLLED, but for already-existing rows we have
    enough state to infer a smarter starting point — preserve the live cohort
    distinction so dashboards don't flatten everyone into a single bucket.
    """
    Scholar = apps.get_model("rims_scholarships", "Scholar")
    Scholar.objects.filter(graduation__isnull=False).update(status="completed")
    Scholar.objects.filter(graduation__isnull=True, status="enrolled").update(status="active")


def _noop(apps, schema_editor):
    pass


class Migration(migrations.Migration):

    dependencies = [
        ("rims_scholarships", "0003_currency_iso4217_choices"),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.AddField(
            model_name="scholar",
            name="status",
            field=models.CharField(
                choices=[
                    ("enrolled", "Enrolled"),
                    ("active", "Active"),
                    ("on_leave", "On leave"),
                    ("withdrawn", "Withdrawn"),
                    ("completed", "Completed"),
                ],
                db_index=True,
                default="enrolled",
                help_text="Lifecycle stage. Use transition_scholar() to change.",
                max_length=16,
            ),
        ),
        migrations.AddField(
            model_name="scholar",
            name="status_changed_at",
            field=models.DateTimeField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name="scholar",
            name="status_changed_by",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="scholar_status_transitions",
                to=settings.AUTH_USER_MODEL,
            ),
        ),
        migrations.AddField(
            model_name="scholar",
            name="withdrawn_reason",
            field=models.TextField(blank=True),
        ),
        migrations.RunPython(_backfill_status, reverse_code=_noop),
    ]
