"""Migrate server info/stats/access tables

Revision ID: ae97b389022a
Revises: 05f7b00bfac8
Create Date: 2021-10-23 09:54:45.993070

"""

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = "ae97b389022a"
down_revision = "05f7b00bfac8"
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("access_log", "postal_code")
    op.drop_column("access_log", "country")

    op.alter_column(
        "access_log",
        "ip_address",
        existing_type=sa.VARCHAR(),
        type_=postgresql.INET(),
        existing_nullable=True,
        postgresql_using="ip_address::inet",
    )
    op.alter_column(
        "access_log", "country_code", existing_type=sa.VARCHAR(), type_=sa.CHAR(length=2), existing_nullable=True
    )
    op.alter_column(
        "access_log",
        "ip_lat",
        existing_type=sa.VARCHAR(),
        type_=sa.Float(),
        existing_nullable=True,
        postgresql_using="ip_lat::double precision",
    )
    op.alter_column(
        "access_log",
        "ip_long",
        existing_type=sa.VARCHAR(),
        type_=sa.Float(),
        existing_nullable=True,
        postgresql_using="ip_long::double precision",
    )

    op.alter_column(
        "server_stats_log",
        "kvstore_count",
        new_column_name="outputstore_count",
        existing_type=sa.INTEGER(),
        type_=sa.BigInteger(),
        existing_nullable=True,
    )

    op.alter_column(
        "server_stats_log", "molecule_count", existing_type=sa.INTEGER(), type_=sa.BigInteger(), existing_nullable=True
    )
    op.alter_column(
        "server_stats_log", "result_count", existing_type=sa.INTEGER(), type_=sa.BigInteger(), existing_nullable=True
    )
    op.alter_column(
        "server_stats_log", "access_count", existing_type=sa.INTEGER(), type_=sa.BigInteger(), existing_nullable=True
    )
    op.alter_column(
        "server_stats_log", "error_count", existing_type=sa.INTEGER(), type_=sa.BigInteger(), existing_nullable=True
    )

    # Rename kv_store in the table information column
    # (for simplicity, just do a text search and replace)
    op.execute(
        sa.text(
            "UPDATE server_stats_log SET db_table_information = replace(db_table_information::text, 'kv_store', 'output_store')::json"
        )
    )

    op.alter_column("access_log", "access_date", existing_type=postgresql.TIMESTAMP(), nullable=False)
    op.alter_column("internal_error_log", "error_date", existing_type=postgresql.TIMESTAMP(), nullable=False)
    op.alter_column("internal_error_log", "qcfractal_version", existing_type=sa.VARCHAR(), nullable=False)

    # ### end Alembic commands ###


def downgrade():
    raise RuntimeError("Cannot downgrade")
