"""Use hash for avatar filenames

Revision ID: 54ce3cde350c
Revises: 4dbd23a3f868
Create Date: 2025-04-14 23:52:38.520744

"""

from pathlib import Path
from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision: str = "54ce3cde350c"
down_revision: Union[str, None] = "4dbd23a3f868"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    from slidge.core import config

    try:
        avatars_root = config.HOME_DIR / "slidge_avatars_v3"
    except AttributeError:
        avatars_root = Path(".")

    connection = op.get_bind()
    avatars = connection.execute(sa.text("SELECT id, filename, hash FROM avatar"))
    for avatar in avatars:
        filename = avatar[1]
        hash_value = avatar[2]
        if filename and hash_value:
            old_file_path = avatars_root / filename
            new_file_path = (avatars_root / hash_value).with_suffix(".png")
            if old_file_path.exists():
                old_file_path.rename(new_file_path)

    with op.batch_alter_table("avatar", schema=None) as batch_op:
        batch_op.drop_column("filename")


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table("avatar", schema=None) as batch_op:
        batch_op.add_column(sa.Column("filename", sa.VARCHAR(), nullable=False))

    # ### end Alembic commands ###
