"""
Data migration to map old observation/inquiry statuses to simplified ones.
"""
from django.db import migrations


def map_observation_statuses(apps, schema_editor):
    Observation = apps.get_model("observations", "Observation")

    # Map old statuses to new ones + set contact_status
    status_mapping = {
        "new": ("open", "not_contacted"),
        "triaged": ("in_progress", "not_contacted"),
        "assigned": ("in_progress", "not_contacted"),
        "contacted": ("in_progress", "contacted"),
        "in_progress": ("in_progress", "not_contacted"),
        "resolved": ("resolved", "not_contacted"),
        "closed": ("closed", "not_contacted"),
        "rejected": ("closed", "not_contacted"),
        "duplicate": ("closed", "not_contacted"),
    }

    for old_status, (new_status, contact_status) in status_mapping.items():
        Observation.objects.filter(status=old_status).update(
            status=new_status, contact_status=contact_status
        )


def map_inquiry_statuses(apps, schema_editor):
    Inquiry = apps.get_model("complaints", "Inquiry")

    # Map old statuses to new ones + set contact_status
    status_mapping = {
        "open": ("open", "not_contacted"),
        "in_progress": ("in_progress", "not_contacted"),
        "contacted": ("in_progress", "contacted"),
        "contacted_no_response": ("in_progress", "contacted_no_response"),
        "resolved": ("resolved", "not_contacted"),
        "closed": ("closed", "not_contacted"),
    }

    for old_status, (new_status, contact_status) in status_mapping.items():
        Inquiry.objects.filter(status=old_status).update(
            status=new_status, contact_status=contact_status
        )


def reverse_map_observation_statuses(apps, schema_editor):
    # Reverse is best-effort; we can't perfectly reconstruct old statuses
    pass


def reverse_map_inquiry_statuses(apps, schema_editor):
    pass


class Migration(migrations.Migration):

    dependencies = [
        ("observations", "0013_simplify_statuses"),
        ("complaints", "0018_simplify_statuses"),
    ]

    operations = [
        migrations.RunPython(map_observation_statuses, reverse_map_observation_statuses),
        migrations.RunPython(map_inquiry_statuses, reverse_map_inquiry_statuses),
    ]
