"""Add expires_at to LoginSession and AuthorizationCode

Revision ID: 2b8bf1c3378e
Revises: f3784e0c8524
Create Date: 2022-07-06 10:44:30.600940

"""

import sqlalchemy as sa
from alembic import op

import fief

# revision identifiers, used by Alembic.
revision = "2b8bf1c3378e"
down_revision = "f3784e0c8524"
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.execute("DELETE FROM fief_authorization_codes")
    op.execute("DELETE FROM fief_login_sessions")

    connection = op.get_bind()

    server_default = None
    if connection.dialect.name == "sqlite":
        server_default = "0"

    op.add_column(
        "fief_authorization_codes",
        sa.Column(
            "expires_at",
            fief.models.generics.TIMESTAMPAware(timezone=True),
            server_default=server_default,
            nullable=False,
        ),
    )
    op.create_index(
        op.f("ix_fief_authorization_codes_expires_at"),
        "fief_authorization_codes",
        ["expires_at"],
        unique=False,
    )
    op.add_column(
        "fief_login_sessions",
        sa.Column(
            "expires_at",
            fief.models.generics.TIMESTAMPAware(timezone=True),
            server_default=server_default,
            nullable=False,
        ),
    )
    op.create_index(
        op.f("ix_fief_login_sessions_expires_at"),
        "fief_login_sessions",
        ["expires_at"],
        unique=False,
    )
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(
        op.f("ix_fief_login_sessions_expires_at"), table_name="fief_login_sessions"
    )
    op.drop_column("fief_login_sessions", "expires_at")
    op.drop_index(
        op.f("ix_fief_authorization_codes_expires_at"),
        table_name="fief_authorization_codes",
    )
    op.drop_column("fief_authorization_codes", "expires_at")
    # ### end Alembic commands ###
