"""added group slug

Revision ID: 04ac51cbe9a4
Revises: b3dbb554ba53
Create Date: 2023-08-06 21:00:34.582905

"""

import sqlalchemy as sa
from slugify import slugify
from sqlalchemy.orm import Session

from alembic import op
from mealie.db.models.group.group import Group

# revision identifiers, used by Alembic.
revision = "04ac51cbe9a4"
down_revision = "b3dbb554ba53"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None


def populate_group_slugs(session: Session):
    groups: list[Group] = session.query(Group).all()
    seen_slugs: set[str] = set()
    for group in groups:
        original_name = group.name
        new_name = original_name
        attempts = 0
        while True:
            slug = slugify(new_name)
            if slug not in seen_slugs:
                break

            attempts += 1
            new_name = f"{original_name} ({attempts})"

        seen_slugs.add(slug)
        session.execute(
            sa.text(f"UPDATE {Group.__tablename__} SET name=:name, slug=:slug WHERE id=:id").bindparams(
                name=new_name, slug=slug, id=group.id
            )
        )

    session.commit()


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column("groups", sa.Column("slug", sa.String(), nullable=True))
    op.create_index(op.f("ix_groups_slug"), "groups", ["slug"], unique=True)
    # ### end Alembic commands ###

    session = Session(bind=op.get_bind())
    populate_group_slugs(session)


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(op.f("ix_groups_slug"), table_name="groups")
    op.drop_column("groups", "slug")
    # ### end Alembic commands ###
