"""Peewee migrations -- 169_MAIN.py.

This is a separate migration because remove_field is retarded and executes before it is time for it
"""

import peewee as pw
from peewee_migrate import Migrator


def assert_only_kgs(database: pw.Database) -> None:
    found = False

    for tablename in ["material"]:
        cursor = database.execute_sql(
            f"SELECT id, unit, name, long_name FROM {tablename} WHERE unit IS NOT NULL AND LOWER(unit) NOT LIKE '%kg%'"
        )
        invalid_materials = cursor.fetchall()

        if invalid_materials:
            found = True
            print(f"Found {len(invalid_materials)} {tablename}s with unit other than kg:")
            for material in invalid_materials:
                print(f"{tablename}(id={material[0]}, unit={material[1]!r}, name={material[2]!r}, long_name={material[3]!r})")

    if found:
        raise pw.IntegrityError("Unable to migrate, data would be invalid. Check logs.")


def migrate(migrator: Migrator, database: pw.Database, *, fake=False):
    """Write your migrations here."""

    migrator.run(assert_only_kgs, database)

    migrator.remove_fields('material', 'unit')

    migrator.rename_field('ordermaterial', 'amount', 'weight')

    migrator.rename_field('batchmaterial', 'amount_recipe', 'weight_recipe')
    migrator.rename_field('batchmaterial', 'amount_rq', 'weight_rq')
    migrator.rename_field('batchmaterial', 'amount_e1', 'weight_e1')

    migrator.rename_field('recipematerial', 'amount', 'weight')

    migrator.rename_field('stockmovement', 'amount', 'weight')


def rollback(migrator: Migrator, database: pw.Database, *, fake=False):
    """Write your rollback migrations here."""

    migrator.rename_field('stockmovement', 'weight', 'amount')

    migrator.rename_field('recipematerial', 'weight', 'amount')

    migrator.rename_field('batchmaterial', 'weight_e1', 'amount_e1')
    migrator.rename_field('batchmaterial', 'weight_rq', 'amount_rq')
    migrator.rename_field('batchmaterial', 'weight_recipe', 'amount_recipe')

    migrator.rename_field('ordermaterial', 'weight', 'amount')

    migrator.add_fields(
        'material',

        unit=pw.TextField(null=True))
