"""Peewee migrations -- 198_MAIN.py.

Frozen pricelist name on ``Order`` and ``MaterialSale``: ``pricelist_name``.

The tax document has to say which pricelist an item was priced from, and a reprint
has to keep saying the same thing after the pricelist is renamed or deleted (the FK
is ``SET NULL``). The name is therefore snapshotted when the pricelist is assigned,
the same way ``Order.customer_name`` / ``recipe_name`` already work. NULL means the
default pricelist. Existing rows are backfilled from the FK they still point at, which
is the closest the old data can get (a pricelist renamed before this migration is
backfilled under its current name; one already deleted stays NULL = default).
"""

import peewee as pw
from peewee_migrate import Migrator


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

    migrator.add_fields(
        'order',

        pricelist_name=pw.TextField(null=True))

    migrator.add_fields(
        'materialsale',

        pricelist_name=pw.TextField(null=True))

    for table in ('order', 'materialsale'):
        migrator.sql(
            f'UPDATE "{table}" SET pricelist_name = '
            f'(SELECT name FROM pricelist WHERE pricelist.id = "{table}".pricelist_id) '
            f'WHERE pricelist_id IS NOT NULL'
        )


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

    migrator.remove_fields('materialsale', 'pricelist_name')

    migrator.remove_fields('order', 'pricelist_name')
