"""Peewee migrations -- 183_MAIN.py.

Rename ``Setup.invoice_fn`` -> ``Setup.taxdocument_fn`` and update the
default value from ``invoice.html`` -> ``taxdocument.html`` to match the
renamed template file.
"""

import peewee as pw
from peewee_migrate import Migrator


def update_default_template_fn(migrator: Migrator) -> None:
    database = migrator.__database__
    database.execute_sql(
        "UPDATE setup SET taxdocument_fn = ? WHERE taxdocument_fn = ?",
        ("taxdocument.html", "invoice.html"),
    )


def restore_default_template_fn(migrator: Migrator) -> None:
    database = migrator.__database__
    database.execute_sql(
        "UPDATE setup SET invoice_fn = ? WHERE invoice_fn = ?",
        ("invoice.html", "taxdocument.html"),
    )


def migrate(migrator: Migrator, database: pw.Database, *, fake: bool = False) -> None:
    migrator.rename_field("setup", "invoice_fn", "taxdocument_fn")
    migrator.run(update_default_template_fn, migrator)


def rollback(migrator: Migrator, database: pw.Database, *, fake: bool = False) -> None:
    migrator.run(restore_default_template_fn, migrator)
    migrator.rename_field("setup", "taxdocument_fn", "invoice_fn")
