"""Peewee migrations -- 108_MAIN.py."""
from typing import cast

import peewee as pw
from peewee_migrate import Migrator

try:
    import playhouse.postgres_ext as pw_pext
except ImportError:
    pass


def recount_distance_driven(migrator: Migrator) -> None:
    Delivery = cast('model.Delivery', migrator.orm['delivery'])
    setup = cast('model.Setup', migrator.orm['setup']).get_or_none()

    factor = 2 if setup is not None and setup.count_distance_doubled else 1

    for record in Delivery.select():
        if record.site_distance:
            record.distance_driven = record.site_distance * factor
            record.save()


def migrate(migrator: Migrator, database: pw.Database, *, fake: bool = False) -> None:
    migrator.run(recount_distance_driven, migrator)


def rollback(migrator: Migrator, database: pw.Database, *, fake: bool = False) -> None:
    pass
