# Generated by Django 2.2.24 on 2021-09-28 19:38

from django.db import migrations
from django.db.models import Case, When, BooleanField, OuterRef, Subquery

from intranet.femida.src.candidates.choices import CONSIDERATION_STATUSES


def fill_consideration_is_last(apps, schema_editor):
    Consideration = apps.get_model('candidates', 'Consideration')
    Consideration.unsafe.update(is_last=False)
    last_considerations = (
        Consideration.unsafe
        .annotate(
            is_active=Case(
                When(state=CONSIDERATION_STATUSES.in_progress, then=True),
                default=False,
                output_field=BooleanField(),
            ),
        )
        .order_by(
            'candidate_id',
            '-is_active',  # при наличии активного рассмотрения возьмем его
            '-finished',  # если его нет, возьмем последнее завершенное
        )
        .distinct('candidate_id')
        .values('id')
    )
    Consideration.unsafe.filter(id__in=last_considerations).update(is_last=True)


def clear_consideration_is_last(apps, schema_editor):
    Consideration = apps.get_model('candidates', 'Consideration')
    Consideration.unsafe.update(is_last=False)


class Migration(migrations.Migration):

    dependencies = [
        ('candidates', '0032_consideration_is_last'),
    ]

    operations = [
        migrations.RunPython(
            code=fill_consideration_is_last,
            reverse_code=clear_consideration_is_last,
        ),
    ]
