"""zjmf finance foundation

Revision ID: 066_zjmf_finance_foundation
Revises: 065_task_run_logs
Create Date: 2026-06-21
"""

import sqlalchemy as sa
from alembic import op


revision = "066_zjmf_finance_foundation"
down_revision = "065_task_run_logs"
branch_labels = None
depends_on = None


def _columns(table_name: str) -> set[str]:
    return {column["name"] for column in sa.inspect(op.get_bind()).get_columns(table_name)}


def _indexes(table_name: str) -> set[str]:
    return {index["name"] for index in sa.inspect(op.get_bind()).get_indexes(table_name)}


def _add_column_if_missing(table_name: str, column: sa.Column) -> None:
    if column.name not in _columns(table_name):
        op.add_column(table_name, column)


def _create_index_if_missing(table_name: str, index_name: str, columns: list[str]) -> None:
    if index_name not in _indexes(table_name):
        op.create_index(index_name, table_name, columns)


def _drop_index_if_exists(table_name: str, index_name: str) -> None:
    if index_name in _indexes(table_name):
        op.drop_index(index_name, table_name=table_name)


def _drop_column_if_exists(table_name: str, column_name: str) -> None:
    if column_name in _columns(table_name):
        op.drop_column(table_name, column_name)


def upgrade() -> None:
    _add_column_if_missing("instances", sa.Column("downstream_token", sa.String(length=64), nullable=True))
    _add_column_if_missing("instances", sa.Column("upstream_invoice_id", sa.Integer(), nullable=True))
    _add_column_if_missing("instances", sa.Column("upstream_payload", sa.JSON(), nullable=True))

    _create_index_if_missing("instances", "ix_instances_downstream_token", ["downstream_token"])
    _create_index_if_missing("instances", "ix_instances_upstream_invoice_id", ["upstream_invoice_id"])


def downgrade() -> None:
    _drop_index_if_exists("instances", "ix_instances_upstream_invoice_id")
    _drop_index_if_exists("instances", "ix_instances_downstream_token")
    _drop_column_if_exists("instances", "upstream_payload")
    _drop_column_if_exists("instances", "upstream_invoice_id")
    _drop_column_if_exists("instances", "downstream_token")
