# -*- coding: utf-8 -*-
from django.db import migrations


def create_function(apps, schema_editor):
    with schema_editor.connection.cursor() as c:
        c.execute('''
            create or replace
            function get_notification_comment(context varchar, response varchar) returns varchar as $$
            select coalesce(
                t.context ->> 'to_address',
                t.context ->> 'supertag',
                t.response -> 'issue' ->> 'key',
                t.context ->> 'queue',
                t.context ->> 'url'
            )
            from (select context::jsonb as context, response::jsonb as response) as t;
            $$ language sql;
        ''')


def drop_function(apps, schema_editor):
    with schema_editor.connection.cursor() as c:
        c.execute('''
            drop function if exists get_notification_comment(varchar, varchar);
        ''')


class Migration(migrations.Migration):
    dependencies = [
        ('surveyme_integration', '0003_forms-8095'),
    ]

    operations = [
        migrations.RunPython(create_function, drop_function),
    ]
