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

from django.db import migrations, models

import hordak
from hordak.defaults import DEFAULT_CURRENCY


def copy_currencies_data(apps, schema_editor):
    # MySQL won't have any old data, because support has only now been added
    if schema_editor.connection.vendor == "postgresql":
        Account = apps.get_model("hordak", "Account")
        table_name = Account._meta.db_table
        with schema_editor.connection.cursor() as cursor:
            # only run this if there is data in the table (in which case we have an ARRAY to migrate);
            # disregard if migrations are being run on a fresh database
            if Account.objects.count() > 0:
                cursor.execute(
                    f"""
                    UPDATE {table_name}
                    SET currencies_json = array_to_json(currencies)::jsonb;
                """
                )
            else:
                cursor.execute(
                    f"""
                    UPDATE {table_name}
                    SET currencies_json = currencies;
                """
                )


def copy_currencies_data_reverse(apps, schema_editor):
    if schema_editor.connection.vendor == "postgresql":
        Account = apps.get_model("hordak", "Account")
        table_name = Account._meta.db_table
        with schema_editor.connection.cursor() as cursor:
            # only run this if there is data in the table (in which case we have an ARRAY to migrate);
            # disregard if migrations are being run on a fresh database
            if Account.objects.count() > 0:
                cursor.execute(
                    f"""
                    UPDATE {table_name}
                    SET currencies = (array_agg(ary)::text[] FROM jsonb_array_elements_text(currencies_json) as ary)
                """
                )


class Migration(migrations.Migration):
    dependencies = [
        ("hordak", "0034_alter_account_currencies_alter_leg_amount_currency"),
    ]

    operations = [
        migrations.AddField(
            model_name="account",
            name="currencies_json",
            field=models.JSONField(
                db_index=True,
                default=(DEFAULT_CURRENCY,),
            ),
        ),
        migrations.RunPython(copy_currencies_data, copy_currencies_data_reverse),
    ]
