"""empty message

Revision ID: 7086ad09e884
Revises: 018130a0bf6c
Create Date: 2023-10-09 18:43:21.964011

"""

import datetime
import uuid

import sqlalchemy as sa
from alembic import op
from sqlalchemy.orm import sessionmaker

from dioptra.restapi.db.custom_types import GUID

try:
    from sqlalchemy.orm import declarative_base

except ImportError:
    from sqlalchemy.ext.declarative import declarative_base

# Migration data models
UpgradeBase = declarative_base()
DowngradeBase = declarative_base()

# revision identifiers, used by Alembic.
revision = "7086ad09e884"
down_revision = "018130a0bf6c"
branch_labels = None
depends_on = None


class UserUpgrade(UpgradeBase):
    __tablename__ = "users"

    user_id = sa.Column(
        sa.BigInteger().with_variant(sa.Integer, "sqlite"), primary_key=True
    )
    alternative_id = sa.Column(GUID())


class UserDowngrade(DowngradeBase):
    __tablename__ = "users"

    user_id = sa.Column(
        sa.BigInteger().with_variant(sa.Integer, "sqlite"), primary_key=True
    )
    user_expire_on = sa.Column(sa.DateTime())


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    bind = op.get_bind()
    Session = sessionmaker(bind=bind)

    with op.batch_alter_table("users", schema=None) as batch_op:
        batch_op.add_column(sa.Column("alternative_id", GUID()))
        batch_op.drop_column("user_expire_on")

    with Session() as session:
        user_stmt = sa.select(UserUpgrade)

        for user in session.scalars(user_stmt):
            user.alternative_id = uuid.uuid4()

        session.commit()

    with op.batch_alter_table("users", schema=None) as batch_op:
        batch_op.alter_column("alternative_id", nullable=False)
        batch_op.create_unique_constraint(
            batch_op.f("uq_users_alternative_id"), ["alternative_id"]
        )

    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    bind = op.get_bind()
    Session = sessionmaker(bind=bind)

    with op.batch_alter_table("users", schema=None) as batch_op:
        batch_op.drop_constraint(batch_op.f("uq_users_alternative_id"), type_="unique")
        batch_op.drop_column("alternative_id")
        batch_op.add_column(sa.Column("user_expire_on", sa.DateTime()))

    with Session() as session:
        user_stmt = sa.select(UserDowngrade)

        for user in session.scalars(user_stmt):
            user.user_expire_on = datetime.datetime(9999, 12, 31, 23, 59, 59)

        session.commit()

    with op.batch_alter_table("users", schema=None) as batch_op:
        batch_op.alter_column("user_expire_on", nullable=False)

    # ### end Alembic commands ###
