"""Initial DB schema

Revision ID: 7fe4633d1aa2
Revises:
Create Date: 2019-09-10 15:52:58.935508

"""
import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision = "7fe4633d1aa2"
down_revision = None
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "tasks",
        sa.Column("id", sa.BigInteger(), nullable=False),
        sa.Column(
            "created",
            sa.DateTime(timezone=True),
            server_default=sa.text("now()"),
            nullable=False,
        ),
        sa.Column("current_log_id", sa.BigInteger(), nullable=True),
        sa.Column("timing_from", sa.DateTime(timezone=True), nullable=False),
        sa.Column("timing_to", sa.DateTime(timezone=True), nullable=False),
        sa.CheckConstraint(
            "timing_from < timing_to", name=op.f("ck_tasks_timig_from_lt_timing_to")
        ),
        sa.PrimaryKeyConstraint("id", name=op.f("pk_tasks")),
        sa.UniqueConstraint("timing_from", name=op.f("uq_tasks_timing_from")),
        sa.UniqueConstraint("timing_to", name=op.f("uq_tasks_timing_to")),
    )
    op.create_table(
        "tasks_log",
        sa.Column("id", sa.BigInteger(), nullable=False),
        sa.Column("task_id", sa.BigInteger(), nullable=False),
        sa.Column(
            "created",
            sa.DateTime(timezone=True),
            server_default=sa.text("now()"),
            nullable=False,
        ),
        sa.Column("executor_id", sa.String(length=128), nullable=False),
        sa.Column(
            "status",
            sa.Enum(
                "accepted_by_normalizer",
                "normalized",
                "accepted_by_charger",
                "charger_received_context",
                "charger_completed_calculation",
                "charger_notified_billing",
                "charger_sent_charged_data",
                "charged",
                name="taskstatus",
            ),
            nullable=False,
        ),
        sa.Column("execution_state", sa.JSON(), nullable=True),
        sa.ForeignKeyConstraint(
            ["task_id"], ["tasks.id"], name=op.f("fk_tasks_log_task_id_tasks")
        ),
        sa.PrimaryKeyConstraint("id", name=op.f("pk_tasks_log")),
        sa.UniqueConstraint(
            "executor_id", "status", name=op.f("uq_tasks_log_executor_id")
        ),
    )
    op.create_foreign_key(
        op.f("fk_tasks_current_log_id_tasks_log"),
        "tasks",
        "tasks_log",
        ["current_log_id"],
        ["id"],
    )
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(
        op.f("fk_tasks_current_log_id_tasks_log"), "tasks", type_="foreignkey"
    )
    op.drop_table("tasks_log")
    op.drop_table("tasks")
    op.execute("DROP TYPE taskstatus")
    # ### end Alembic commands ###
