# Generated by Django 2.1 on 2018-08-23 08:52

from django.db import migrations, models


def init_delivery_at(apps, schema_editor):

    db_alias = schema_editor.connection.alias
    request_model = apps.get_model('api', 'Request')

    qs = (
        request_model.objects.using(db_alias)
        .only('id')
        .annotate(new_delivery_at=models.Max('quotes__delivery_at'))
        .filter(new_delivery_at__isnull=False)
    )

    for request in qs:
        request.delivery_at = request.new_delivery_at
        request.save(update_fields=['delivery_at'])


def do_nothing(apps, schema_editor):
    pass


SQL_CREATE = """
CREATE OR REPLACE FUNCTION aggregate_delivery_at() RETURNS TRIGGER AS $$
    BEGIN
        UPDATE api_request
        SET delivery_at = (
          SELECT delivery_at
          FROM api_quote
          WHERE request_id=NEW.request_id AND is_deleted=false
          ORDER BY delivery_at DESC NULLS LAST
          LIMIT 1
        )
        WHERE id=NEW.request_id;
        RETURN NEW;
    END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS trigger_update_delivery_at ON api_quote;
CREATE TRIGGER trigger_update_delivery_at
AFTER UPDATE ON api_quote
FOR EACH ROW
WHEN (OLD.delivery_at IS DISTINCT FROM NEW.delivery_at)
EXECUTE PROCEDURE aggregate_delivery_at();
"""


SQL_DROP = """
DROP FUNCTION IF EXISTS aggregate_delivery_at() CASCADE;
"""


class Migration(migrations.Migration):

    dependencies = [('api', '0014_request_show_assignee')]

    operations = [
        migrations.AddField(
            model_name='request',
            name='delivery_at',
            field=models.DateField(
                null=True, verbose_name='MODEL_REQUEST::DELIVERY_AT'
            ),
        ),
        migrations.RunPython(init_delivery_at, do_nothing),
        migrations.RunSQL(sql=SQL_CREATE, reverse_sql=SQL_DROP, elidable=False),
    ]
