"""add dataset row created_at and latest_version

Revision ID: 7fb45748e807
Revises: 897c39909e73
Create Date: 2025-10-20 13:02:00.804744

"""

import sqlalchemy as sa

from alembic import op

# revision identifiers, used by Alembic.
revision = "7fb45748e807"
down_revision = "897c39909e73"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column(
        "dataset_version_rows",
        sa.Column("created_at", sa.TIMESTAMP(), nullable=True),
    )
    op.execute(
        """
        UPDATE dataset_version_rows
        SET created_at = CURRENT_TIMESTAMP
        WHERE created_at is null
        """,
    )
    op.alter_column("dataset_version_rows", "created_at", nullable=False)
    op.add_column(
        "datasets",
        sa.Column("latest_version_number", sa.Integer(), nullable=True),
    )
    op.execute(
        """
        UPDATE datasets
        SET latest_version_number = (
            SELECT MAX(version_number)
            FROM dataset_versions
            WHERE dataset_versions.dataset_id = datasets.id
        )
        """,
    )
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("datasets", "latest_version_number")
    op.drop_column("dataset_version_rows", "created_at")
    # ### end Alembic commands ###
