# SPDX-FileCopyrightText: 2023 Marlon W (Mawoka)
#
# SPDX-License-Identifier: MPL-2.0

"""user avatar

Revision ID: ff573859eb32
Revises: da778d551bf4
Create Date: 2022-07-05 20:36:44.858963

"""
import asyncio

from alembic import op
import sqlalchemy as sa
from sqlalchemy.orm import Session
from sqlalchemy.sql.functions import user

from classquiz.helpers.avatar import gzipped_user_avatar
import ormar
from classquiz.db.models import User
from classquiz.db import metadata, database

# revision identifiers, used by Alembic.
revision = "ff573859eb32"
down_revision = "da778d551bf4"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column("users", sa.Column("avatar", sa.LargeBinary(length=25000), nullable=True))
    conn = op.get_bind()
    session = Session(bind=conn)
    res = session.execute("SELECT id from users;")
    for row in res:
        user_id = str(row).strip(",.'()")
        avatar = gzipped_user_avatar().hex()
        session.execute(
            sa.sql.text("UPDATE users SET avatar = (decode(:avatar, 'hex')) WHERE users.id=:user_id"),
            {"user_id": user_id, "avatar": avatar},
        )
    op.alter_column("users", "avatar", nullable=False)

    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("users", "avatar")
    # ### end Alembic commands ###
