"""Peewee migrations -- 195_MAIN.py.

Direct material sales feature:

* new ``MaterialSale`` table (a direct sale of raw material to a customer),
* new ``PricelistMaterial`` table (per-kg material prices, default + per-pricelist),
* new ``StockMovement.material_sale`` nullable FK (sale-driven stock movements),
* new ``State.materialsale_num_counter`` counter column,
* new ``Setup.materialsale_number_prefix``, snapshotted into ``MaterialSale.number_prefix``
  at creation so a later Setup change does not rewrite already-issued sales.

Only the changes above are intentional; unrelated index drift the auto-generator
may surface for other tables is deliberately left out.
"""

import peewee as pw
from peewee_migrate import Migrator


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

    @migrator.create_model
    class MaterialSale(pw.Model):
        id = pw.AutoField()
        _search_string = pw.TextField(null=True)
        audit_created_by = pw.TextField(null=True)
        audit_created_at = pw.IntegerField(default=0)
        audit_changed_by = pw.TextField(null=True)
        audit_changed_at = pw.IntegerField(default=0)
        t = pw.IntegerField()
        number = pw.IntegerField()
        number_prefix = pw.TextField(default="")
        customer = pw.ForeignKeyField(column_name="customer_id", field="id", model=migrator.orm["customer"], null=True, on_delete="RESTRICT")
        material = pw.ForeignKeyField(column_name="material_id", field="id", model=migrator.orm["material"], on_delete="RESTRICT")
        pricelist = pw.ForeignKeyField(column_name="pricelist_id", field="id", model=migrator.orm["pricelist"], null=True, on_delete="SET NULL")
        weight = pw.DoubleField()
        unit_price = pw.DoubleField()
        taxdocument = pw.ForeignKeyField(column_name="taxdocument_id", field="id", model=migrator.orm["taxdocument"], null=True, on_delete="SET NULL")
        note = pw.TextField(default=None, null=True)

        class Meta:
            table_name = "materialsale"

    @migrator.create_model
    class PricelistMaterial(pw.Model):
        id = pw.AutoField()
        _search_string = pw.TextField(null=True)
        pricelist = pw.ForeignKeyField(column_name="pricelist_id", field="id", model=migrator.orm["pricelist"], null=True, on_delete="CASCADE")
        material = pw.ForeignKeyField(column_name="material_id", field="id", model=migrator.orm["material"], on_delete="CASCADE")
        price = pw.DoubleField()

        class Meta:
            table_name = "pricelistmaterial"
            indexes = [(("pricelist", "material"), True)]

    migrator.add_fields("state", materialsale_num_counter=pw.IntegerField(default=0))

    migrator.add_fields("setup", materialsale_number_prefix=pw.TextField(default=""))

    migrator.add_fields(
        "stockmovement",
        material_sale=pw.ForeignKeyField(column_name="material_sale_id", field="id", model=migrator.orm["materialsale"], null=True, on_delete="CASCADE"),
    )


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

    migrator.remove_fields("stockmovement", "material_sale")

    migrator.remove_fields("setup", "materialsale_number_prefix")

    migrator.remove_fields("state", "materialsale_num_counter")

    migrator.remove_model("pricelistmaterial")

    migrator.remove_model("materialsale")
