"""Peewee migrations -- 131_MAIN.py."""

import peewee as pw
from peewee_migrate import Migrator


def migrate(migrator: Migrator, database: pw.Database, *, fake: bool = False) -> None:
    """Write your migrations here."""
    
    migrator.add_fields(
        'order',

        distance_driven=pw.DoubleField(null=True),
        construction_site_distance=pw.DoubleField(null=True))

    migrator.add_fields(
        'delivery',

        price_per_km_modified=pw.DoubleField(null=True),
        transport_zone_modified=pw.ForeignKeyField(column_name='transport_zone_modified_id', field='id', model=migrator.orm['transportzone'], null=True, on_delete='RESTRICT'))

    migrator.sql("""
        UPDATE "order"
        SET distance_driven = "delivery".distance_driven,
            construction_site_distance = "delivery".site_distance
        FROM (SELECT order_id, distance_driven, site_distance FROM "delivery") AS "delivery"
        WHERE "order".id = "delivery".order_id;
    """)

    migrator.sql("""
        UPDATE "delivery"
        SET price_per_km_modified = "order".price_per_km_modified,
            transport_zone_modified_id = "order".transport_zone_modified_id
        FROM (SELECT id, price_per_km_modified, transport_zone_modified_id FROM "order") AS "order"
        WHERE "delivery".order_id = "order".id;
    """)

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

    migrator.remove_fields('delivery', 'distance_driven', 'site_distance')


def rollback(migrator: Migrator, database: pw.Database, *, fake: bool = False) -> None:
    """Write your rollback migrations here."""
    
    migrator.add_fields(
        'delivery',

        distance_driven=pw.DoubleField(null=True),
        site_distance=pw.DoubleField(null=True))

    migrator.add_fields(
        'order',

        price_per_km_modified=pw.DoubleField(null=True))

    migrator.sql("""
        UPDATE "delivery"
        SET distance_driven = "order".distance_driven,
            site_distance = "order".construction_site_distance
        FROM (SELECT delivery_id, distance_driven, construction_site_distance FROM "order") AS "order"
        WHERE "delivery".id = "order".delivery_id;
    """)

    migrator.sql("""
        UPDATE "order"
        SET price_per_km_modified = "delivery".price_per_km_modified
        FROM (SELECT id, price_per_km_modified FROM "delivery") AS "delivery"
        WHERE "delivery".id = "order".delivery_id;
    """)

    migrator.remove_fields('delivery', 'price_per_km_modified', 'transport_zone_modified')

    migrator.remove_fields('order', 'distance_driven', 'construction_site_distance')
