"""Extension unaccent

Revision ID: d84bc592584e
Revises: b8df1b913c79
Create Date: 2023-06-01 13:46:52.927951

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.orm import sessionmaker  # added by ev


# revision identifiers, used by Alembic.
revision = "d84bc592584e"
down_revision = "b8df1b913c79"
branch_labels = None
depends_on = None

Session = sessionmaker()


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###

    bind = op.get_bind()
    session = Session(bind=bind)
    # Ajout extension pour recherches sans accents:
    # erreur: doit s'executer en superuser
    # session.execute(sa.text("""CREATE EXTENSION IF NOT EXISTS "unaccent";"""))

    # Clé étrangère sur identite
    session.execute(
        sa.text(
            """UPDATE are_stages_apprentissages
        SET etudid = NULL
        WHERE are_stages_apprentissages.etudid NOT IN (
        SELECT id
        FROM Identite
        );
        """
        )
    )
    with op.batch_alter_table("are_stages_apprentissages", schema=None) as batch_op:
        batch_op.create_foreign_key(
            "are_stages_apprentissages_etudid_fkey",
            "identite",
            ["etudid"],
            ["id"],
            ondelete="CASCADE",
        )

    # Les montants de taxe en float:
    with op.batch_alter_table("are_taxe_apprentissage", schema=None) as batch_op:
        batch_op.alter_column(
            "montant",
            existing_type=sa.INTEGER(),
            type_=sa.Float(),
            existing_nullable=True,
        )
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table("are_taxe_apprentissage", schema=None) as batch_op:
        batch_op.alter_column(
            "montant",
            existing_type=sa.Float(),
            type_=sa.INTEGER(),
            existing_nullable=True,
        )

    with op.batch_alter_table("are_stages_apprentissages", schema=None) as batch_op:
        batch_op.drop_constraint(
            "are_stages_apprentissages_etudid_fkey", type_="foreignkey"
        )

    # ### end Alembic commands ###
