"""Peewee migrations -- 196_MAIN.py.

Optional construction site / vehicle / driver on a direct material sale:

* new ``MaterialSale.construction_site`` nullable FK to ``ConstructionSite``,
* new ``MaterialSale.vehicle`` nullable FK to ``Car``,
* new ``MaterialSale.driver`` nullable FK to ``Driver``.

All three are informational (where the material went, who collected it) and may
stay empty - a walk-in sale has no site, and the customer's own truck is not in
our Car table. Only the changes above are intentional; unrelated index drift the
auto-generator surfaced for ``surcharge`` and ``specialprice`` 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."""

    # No explicit add_index: add_fields already creates materialsale_{vehicle,driver}_id for the
    # foreign keys, and the auto-generator's extra add_index calls fail on "index already exists".
    migrator.add_fields(
        "materialsale",
        construction_site=pw.ForeignKeyField(
            column_name="construction_site_id", field="id", model=migrator.orm["constructionsite"], null=True, on_delete="SET NULL"
        ),
        vehicle=pw.ForeignKeyField(column_name="vehicle_id", field="id", model=migrator.orm["car"], null=True, on_delete="SET NULL"),
        driver=pw.ForeignKeyField(column_name="driver_id", field="id", model=migrator.orm["driver"], null=True, on_delete="SET NULL"),
    )


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

    migrator.remove_fields("materialsale", "construction_site", "vehicle", "driver")
