# Generated by Django 4.2 on 2023-05-16 01:42

from django.db import migrations


def create_triggers(apps, schema_editor):
    if schema_editor.connection.vendor == "postgresql":
        schema_editor.execute(
            """
            CREATE OR REPLACE FUNCTION check_leg_and_account_currency_match()
                RETURNS trigger AS
            $$
            DECLARE
                account RECORD;
            BEGIN

                IF (TG_OP = 'DELETE') THEN
                    RETURN OLD;
                END IF;

                PERFORM * FROM hordak_account WHERE id = NEW.account_id AND currencies::jsonb @> to_jsonb(ARRAY[NEW.amount_currency]::text[]);

                IF NOT FOUND THEN
                    SELECT * INTO account FROM hordak_account WHERE id = NEW.account_id;

                    RAISE EXCEPTION 'Destination Account#%% does not support currency %%. Account currencies: %%', account.id, NEW.amount_currency, account.currencies;
                END IF;

                RETURN NEW;
            END;
            $$
            LANGUAGE plpgsql
        """
        )
    elif schema_editor.connection.vendor == "mysql":
        pass  # nothing to do here, we've already created the procedure in 0007_auto_20161209_0111.py
    else:
        raise NotImplementedError(
            "Unsupported database vendor: %s" % schema_editor.connection.vendor
        )


def drop_triggers(apps, schema_editor):
    if schema_editor.connection.vendor == "postgresql":
        # Recreate check_leg_and_account_currency_match as it was in migration 0007
        schema_editor.execute(
            """
            CREATE OR REPLACE FUNCTION check_leg_and_account_currency_match()
                RETURNS trigger AS
            $$
            DECLARE

            BEGIN

                IF (TG_OP = 'DELETE') THEN
                    RETURN OLD;
                END IF;

                PERFORM * FROM hordak_account WHERE id = NEW.account_id AND NEW.amount_currency = ANY(currencies);

                IF NOT FOUND THEN
                    RAISE EXCEPTION 'Destination account does not support currency %%', NEW.amount_currency;
                END IF;

                RETURN NEW;
            END;
            $$
            LANGUAGE plpgsql
        """
        )
    elif schema_editor.connection.vendor == "mysql":
        pass
    else:
        raise NotImplementedError(
            "Unsupported database vendor: %s" % schema_editor.connection.vendor
        )


class Migration(migrations.Migration):
    dependencies = [
        (
            "hordak",
            "0036_remove_currencies_and_rename_account_currencies_json_to_currencies",
        ),
    ]

    operations = [
        migrations.RunPython(create_triggers, drop_triggers),
    ]
