"""add table campaigns_change_log

Revision ID: 33421e19542d
Revises: 6c61b65786ce
Create Date: 2020-05-18 10:16:32.628563

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

import maps_adv.adv_store.v2.lib.db.columns
import maps_adv.adv_store.v2.lib.db.constraints

# revision identifiers, used by Alembic.
revision = "33421e19542d"
down_revision = "6c61b65786ce"
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    campaignstatusenum = sa.String()
    campaignstatusenum.__visit_name__ = "campaignstatusenum"

    op.create_table(
        "campaigns_change_log",
        sa.Column("id", sa.BigInteger(), nullable=False),
        sa.Column(
            "created_at",
            maps_adv.adv_store.v2.lib.db.columns.DateTimeTZ(),
            server_default=sa.text("now()"),
            nullable=False,
        ),
        sa.Column("campaign_id", sa.BigInteger(), nullable=False),
        sa.Column("author_id", sa.BigInteger(), nullable=True),
        sa.Column("status", campaignstatusenum, nullable=False),
        sa.Column(
            "system_metadata",
            postgresql.JSONB(astext_type=sa.Text()),
            server_default="{}",
            nullable=False,
        ),
        sa.Column(
            "state_before",
            postgresql.JSONB(astext_type=sa.Text()),
            server_default="{}",
            nullable=False,
        ),
        sa.Column(
            "state_after",
            postgresql.JSONB(astext_type=sa.Text()),
            server_default="{}",
            nullable=False,
        ),
        sa.Column("is_latest", sa.Boolean(), nullable=False),
        sa.CheckConstraint(
            "jsonb_typeof(state_after) = 'object'",
            name=op.f("ck_campaigns_change_log_state_after_jsonb_object"),
        ),
        sa.CheckConstraint(
            "jsonb_typeof(state_before) = 'object'",
            name=op.f("ck_campaigns_change_log_state_before_jsonb_object"),
        ),
        sa.ForeignKeyConstraint(
            ["campaign_id"],
            ["campaign.id"],
            name=op.f("fk_campaigns_change_log_campaign_id_campaign"),
        ),
        sa.PrimaryKeyConstraint("id", name=op.f("pk_campaigns_change_log")),
    )
    op.create_index(
        "ix_campaigns_change_log_campaign_id_hash_partial_is_latest",
        "campaigns_change_log",
        ["campaign_id"],
        unique=False,
        postgresql_using="btree",
        postgresql_where=sa.text("is_latest"),
    )
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(
        "ix_campaigns_change_log_campaign_id_hash_partial_is_latest",
        table_name="campaigns_change_log",
    )
    op.drop_table("campaigns_change_log")
    # ### end Alembic commands ###
