"""Rename `object_storage_meta` to `object_storage_namespace`

Revision ID: b6f3b3c69d16
Revises: 29bbf3830309
Create Date: 2025-08-28 05:09:38.548556

"""

import sqlalchemy as sa
from alembic import op

from ai.backend.manager.models.base import GUID

# revision identifiers, used by Alembic.
revision = "b6f3b3c69d16"
down_revision = "29bbf3830309"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint("uq_storage_id_bucket", "object_storage_meta")

    op.create_table(
        "object_storage_namespace",
        sa.Column("id", GUID(), server_default=sa.text("uuid_generate_v4()"), nullable=False),  # noqa: F821
        sa.Column("storage_id", GUID(), nullable=False),
        sa.Column("bucket", sa.String(), nullable=False),
        sa.PrimaryKeyConstraint("id", name=op.f("pk_object_storage_namespace")),
        sa.UniqueConstraint("storage_id", "bucket", name="uq_storage_id_bucket"),
    )

    # Migrate data from object_storage_meta to object_storage_namespace
    connection = op.get_bind()
    connection.execute(
        sa.text("""
            INSERT INTO object_storage_namespace (id, storage_id, bucket)
            SELECT id, storage_id, bucket FROM object_storage_meta
        """)
    )

    op.drop_table("object_storage_meta")
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint("uq_storage_id_bucket", "object_storage_namespace")

    op.create_table(
        "object_storage_meta",
        sa.Column(
            "id",
            GUID(),
            server_default=sa.text("uuid_generate_v4()"),
            autoincrement=False,
            nullable=False,
        ),
        sa.Column("storage_id", GUID(), autoincrement=False, nullable=False),
        sa.Column("bucket", sa.String(), autoincrement=False, nullable=False),
        sa.PrimaryKeyConstraint("id", name="pk_object_storage_meta"),
        sa.UniqueConstraint("storage_id", "bucket", name="uq_storage_id_bucket"),
    )

    # Migrate data from object_storage_namespace to object_storage_meta
    connection = op.get_bind()
    connection.execute(
        sa.text("""
            INSERT INTO object_storage_meta (id, storage_id, bucket)
            SELECT id, storage_id, bucket FROM object_storage_namespace
        """)
    )

    op.drop_table("object_storage_namespace")
    # ### end Alembic commands ###
