# pylint: disable=invalid-name
"""BackgroundTask

Revision ID: 8b6b89bfbc97
Revises: c2b90f147183
Create Date: 2021-01-26 18:51:57.731262+00:00

"""
import uuid
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = "8b6b89bfbc97"
down_revision = "c2b90f147183"
branch_labels = None
depends_on = None


def backfill():  # pragma: no cover
    # Backfill a background task for all previous rounds
    connection = op.get_bind()
    rounds = connection.execute("SELECT id, election_id, created_at FROM round")
    for round_id, election_id, created_at in rounds.fetchall():
        (new_task_id,) = connection.execute(
            f"""
            INSERT INTO background_task (
                id,
                task_name,
                payload,
                created_at,
                updated_at,
                started_at,
                completed_at,
                error
            )
            VALUES (
                '{str(uuid.uuid4())}',
                'draw_sample',
                '{{"round_id": "{round_id}", "election_id": "{election_id}"}}',
                '{created_at}',
                '{created_at}',
                '{created_at}',
                '{created_at}',
                null
            )
            RETURNING id
            """
        ).fetchone()
        connection.execute(
            f"""
            UPDATE round
            SET draw_sample_task_id = '{new_task_id}'
            WHERE id = '{round_id}'
            """
        )


def upgrade():
    op.create_table(
        "background_task",
        sa.Column("created_at", sa.DateTime(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), nullable=False),
        sa.Column("id", sa.String(length=200), nullable=False),
        sa.Column("task_name", sa.String(length=200), nullable=False),
        sa.Column("payload", sa.JSON(), nullable=False),
        sa.Column("started_at", sa.DateTime(), nullable=True),
        sa.Column("completed_at", sa.DateTime(), nullable=True),
        sa.Column("error", sa.Text(), nullable=True),
        sa.PrimaryKeyConstraint("id", name=op.f("background_task_pkey")),
    )
    op.add_column(
        "round", sa.Column("draw_sample_task_id", sa.String(length=200), nullable=True)
    )
    op.create_foreign_key(
        op.f("round_draw_sample_task_id_fkey"),
        "round",
        "background_task",
        ["draw_sample_task_id"],
        ["id"],
        ondelete="cascade",
    )
    backfill()


def downgrade():  # pragma: no cover
    pass
    # # ### commands auto generated by Alembic - please adjust! ###
    # op.drop_constraint(
    #     op.f("round_draw_sample_task_id_fkey"), "round", type_="foreignkey"
    # )
    # op.drop_column("round", "draw_sample_task_id")
    # op.drop_table("background_task")
    # # ### end Alembic commands ###
