"""Add Stipend lifecycle fields so scholar withdrawal can cancel pending payments.

P0 (RIMS assessment §3 #9 / SRS §4.3.4) — Stipend rows previously had no
status, so a withdrawn scholar's scheduled stipends could still post. Add
``status`` (default PAID for back-compat), plus cancellation metadata.
"""

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


def _backfill_status(apps, schema_editor):
    """Mark every existing stipend row as PAID — they represent posted payments."""
    Stipend = apps.get_model("rims_scholarships", "Stipend")
    Stipend.objects.filter(status="").update(status="paid")
    Stipend.objects.filter(status__isnull=True).update(status="paid")


def _noop(apps, schema_editor):
    pass


class Migration(migrations.Migration):

    dependencies = [
        ("rims_scholarships", "0004_scholar_status"),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.AddField(
            model_name="stipend",
            name="status",
            field=models.CharField(
                choices=[
                    ("pending", "Pending"),
                    ("paid", "Paid"),
                    ("cancelled", "Cancelled"),
                ],
                db_index=True,
                default="paid",
                max_length=12,
            ),
        ),
        migrations.AddField(
            model_name="stipend",
            name="cancelled_at",
            field=models.DateTimeField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name="stipend",
            name="cancelled_reason",
            field=models.TextField(blank=True),
        ),
        migrations.AddField(
            model_name="stipend",
            name="cancelled_by",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="stipends_cancelled",
                to=settings.AUTH_USER_MODEL,
            ),
        ),
        migrations.RunPython(_backfill_status, reverse_code=_noop),
    ]
