"""polymorthic run_metadata [8ed03137cacc].

Revision ID: 8ed03137cacc
Revises: a91762e6be36
Create Date: 2023-11-17 16:19:34.281692

"""

import sqlalchemy as sa
import sqlmodel
from alembic import op
from sqlmodel import Session

# revision identifiers, used by Alembic.
revision = "8ed03137cacc"
down_revision = "a91762e6be36"
branch_labels = None
depends_on = None


def upgrade() -> None:
    """Upgrade database schema and/or data, creating a new revision."""
    # ### commands auto generated by Alembic - please adjust! ###

    with op.batch_alter_table("run_metadata", schema=None) as batch_op:
        batch_op.add_column(
            sa.Column("resource_type", sa.VARCHAR(length=255), nullable=True)
        )
        batch_op.add_column(
            sa.Column(
                "resource_id", sqlmodel.sql.sqltypes.GUID(), nullable=True
            )
        )
        batch_op.drop_constraint(
            "fk_run_metadata_step_run_id_step_run", type_="foreignkey"
        )
        batch_op.drop_constraint(
            "fk_run_metadata_artifact_version_id_artifact_version",
            type_="foreignkey",
        )
        batch_op.drop_constraint(
            "fk_run_metadata_pipeline_run_id_pipeline_run", type_="foreignkey"
        )

    with Session(bind=op.get_bind()) as session:
        stmt = sa.text(
            """
            UPDATE run_metadata
            SET resource_id = pipeline_run_id,
                resource_type = 'pipeline_run'
            WHERE pipeline_run_id IS NOT NULL
            """
        )
        session.execute(stmt)
        stmt = sa.text(
            """
            UPDATE run_metadata
            SET resource_id = step_run_id,
                resource_type = 'step_run'
            WHERE step_run_id IS NOT NULL
            """
        )
        session.execute(stmt)
        stmt = sa.text(
            """
            UPDATE run_metadata
            SET resource_id = artifact_version_id,
                resource_type = 'artifact_version'
            WHERE artifact_version_id IS NOT NULL
            """
        )
        session.execute(stmt)
        session.commit()

    with op.batch_alter_table("run_metadata", schema=None) as batch_op:
        batch_op.alter_column(
            "resource_type",
            existing_type=sa.VARCHAR(length=255),
            existing_nullable=True,
            nullable=False,
        )
        batch_op.alter_column(
            "resource_id",
            existing_type=sqlmodel.sql.sqltypes.GUID(),
            existing_nullable=True,
            nullable=False,
        )
        batch_op.drop_column("step_run_id")
        batch_op.drop_column("artifact_version_id")
        batch_op.drop_column("pipeline_run_id")

    # ### end Alembic commands ###


def downgrade() -> None:
    """Downgrade database schema and/or data back to the previous revision."""
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table("run_metadata", schema=None) as batch_op:
        batch_op.add_column(
            sa.Column("pipeline_run_id", sa.CHAR(length=32), nullable=True)
        )
        batch_op.add_column(
            sa.Column("artifact_version_id", sa.CHAR(length=32), nullable=True)
        )
        batch_op.add_column(
            sa.Column("step_run_id", sa.CHAR(length=32), nullable=True)
        )
        batch_op.create_foreign_key(
            "fk_run_metadata_pipeline_run_id_pipeline_run",
            "pipeline_run",
            ["pipeline_run_id"],
            ["id"],
            ondelete="CASCADE",
        )
        batch_op.create_foreign_key(
            "fk_run_metadata_artifact_version_id_artifact_version",
            "artifact_version",
            ["artifact_version_id"],
            ["id"],
            ondelete="CASCADE",
        )
        batch_op.create_foreign_key(
            "fk_run_metadata_step_run_id_step_run",
            "step_run",
            ["step_run_id"],
            ["id"],
            ondelete="CASCADE",
        )

    with Session(bind=op.get_bind()) as session:
        stmt = sa.text(
            """
            UPDATE run_metadata
            SET pipeline_run_id = resource_id
            WHERE resource_type = 'pipeline_run'
            """
        )
        session.execute(stmt)
        stmt = sa.text(
            """
            UPDATE run_metadata
            SET step_run_id = resource_id
            WHERE resource_type = 'step_run'
            """
        )
        session.execute(stmt)
        stmt = sa.text(
            """
            UPDATE run_metadata
            SET artifact_version_id = resource_id
            WHERE resource_type = 'artifact_version'
            """
        )
        session.execute(stmt)
        session.commit()

    with op.batch_alter_table("run_metadata", schema=None) as batch_op:
        batch_op.drop_column("resource_id")
        batch_op.drop_column("resource_type")

    # ### end Alembic commands ###
