"""Phase 2.1b: richer external maintenance passages."""
from alembic import op
import sqlalchemy as sa

revision = "i4d5e6f7a8b9"
down_revision = "h3c4d5e6f7a8"
branch_labels = None
depends_on = None


def upgrade():
    op.add_column("contract_visits", sa.Column("lot_task_id", sa.Integer(), nullable=True))
    op.add_column("contract_visits", sa.Column("passage_mode", sa.String(20), nullable=False, server_default="appointment"))
    op.add_column("contract_visits", sa.Column("start_time", sa.Time(), nullable=True))
    op.add_column("contract_visits", sa.Column("end_time", sa.Time(), nullable=True))
    op.add_column("contract_visits", sa.Column("window_start", sa.Date(), nullable=True))
    op.add_column("contract_visits", sa.Column("window_end", sa.Date(), nullable=True))
    op.add_column("contract_visits", sa.Column("actual_date", sa.Date(), nullable=True))
    op.add_column("contract_visits", sa.Column("arrival_at", sa.DateTime(), nullable=True))
    op.add_column("contract_visits", sa.Column("accompaniment_mode", sa.String(20), nullable=False, server_default="none"))
    op.add_column("contract_visits", sa.Column("accompaniment_minutes", sa.Integer(), nullable=True))
    op.add_column("contract_visits", sa.Column("technician_id", sa.Integer(), nullable=True))
    op.create_foreign_key("fk_contract_visits_lot_task", "contract_visits", "lot_tasks", ["lot_task_id"], ["id"], ondelete="SET NULL")
    op.create_foreign_key("fk_contract_visits_technician", "contract_visits", "users", ["technician_id"], ["id"], ondelete="SET NULL")
    op.create_index("ix_contract_visits_lot_task_id", "contract_visits", ["lot_task_id"])


def downgrade():
    op.drop_index("ix_contract_visits_lot_task_id", table_name="contract_visits")
    op.drop_constraint("fk_contract_visits_technician", "contract_visits", type_="foreignkey")
    op.drop_constraint("fk_contract_visits_lot_task", "contract_visits", type_="foreignkey")
    for name in ("technician_id", "accompaniment_minutes", "accompaniment_mode", "arrival_at", "actual_date", "window_end", "window_start", "end_time", "start_time", "passage_mode", "lot_task_id"):
        op.drop_column("contract_visits", name)
