"""add_db_replication_state

Revision ID: 1fc0ac1a6e64
Revises: d07783bd94f

"""

# revision identifiers, used by Alembic.
revision = "1fc0ac1a6e64"
down_revision = "d07783bd94f"

import sqlalchemy as sa
from sqlalchemy import sql

from alembic import op

cel_table = sql.table("cel", sql.column("id"))
queue_log_table = sql.table("queue_log", sql.column("id"))
qualification_answers_table = sql.table("qualification_answers", sql.column("id"))
callback_request_table = sql.table("callback_request", sql.column("reference_number"))

replication_state_table = sql.table(
    "replication_state", sql.column("name"), sql.column("ref"), sql.column("val")
)


def get_value(query):
    return op.get_bind().execute(query).scalar()


def upgrade():
    op.create_table(
        "replication_state",
        sa.Column("name", sa.String(128), nullable=False),
        sa.Column("ref", sa.String(128), nullable=False),
        sa.Column("val", sa.Integer, nullable=False),
        sa.PrimaryKeyConstraint("name"),
    )

    cel_last_id = sql.select([sa.func.coalesce(sa.func.max(cel_table.c.id), 0)])
    queue_log_last_id = sql.select(
        [sa.func.coalesce(sa.func.max(queue_log_table.c.id), 0)]
    )
    qualification_answers_last_id = sql.select(
        [sa.func.coalesce(sa.func.max(qualification_answers_table.c.id), 0)]
    )
    callback_request_last_ref = sql.select(
        [sa.func.coalesce(sa.func.max(callback_request_table.c.reference_number), 0)]
    )

    op.bulk_insert(
        replication_state_table,
        [
            {"name": "cel", "ref": "id", "val": get_value(cel_last_id)},
            {"name": "queue_log", "ref": "id", "val": get_value(queue_log_last_id)},
            {
                "name": "qualification_answers",
                "ref": "id",
                "val": get_value(qualification_answers_last_id),
            },
            {
                "name": "callback_request",
                "ref": "reference_number",
                "val": get_value(callback_request_last_ref),
            },
        ],
    )


def downgrade():
    op.drop_table("replication_state")
