"""Association UEs <-> parcours

Revision ID: 054dd6133b9c
Revises: 6520faf67508
Create Date: 2023-03-30 19:40:50.575293

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


# revision identifiers, used by Alembic.
revision = "054dd6133b9c"
down_revision = "6520faf67508"
branch_labels = None
depends_on = None

Session = sessionmaker()


def upgrade():
    """Passe d'une relation UE - Parcours one-to-many à une relation many-to-many
    crée la table d'association, copie l'éventuelle relation existante
    puis supprime la clé étrangère parcour_id
    """
    op.create_table(
        "ue_parcours",
        sa.Column("ue_id", sa.Integer(), nullable=False),
        sa.Column("parcours_id", sa.Integer(), nullable=False),
        sa.Column("ects", sa.Float(), nullable=True),
        sa.ForeignKeyConstraint(
            ["parcours_id"], ["apc_parcours.id"], ondelete="CASCADE"
        ),
        sa.ForeignKeyConstraint(["ue_id"], ["notes_ue.id"], ondelete="CASCADE"),
        sa.PrimaryKeyConstraint("ue_id", "parcours_id"),
    )

    #
    bind = op.get_bind()
    session = Session(bind=bind)
    session.execute(
        sa.text(
            """
        INSERT INTO ue_parcours
        SELECT id as ue_id, parcour_id as parcours_id
        FROM notes_ue
        WHERE parcour_id is not NULL;
        """
        )
    )
    session.commit()
    op.drop_column("notes_ue", "parcour_id")

    # Numeros non nullables
    for table in (
        "apc_competence",
        "apc_parcours",
        "notes_form_modalites",
        "notes_ue",
        "notes_matieres",
        "notes_modules",
        "notes_evaluation",
        "partition",
        "group_descr",
    ):
        session.execute(
            sa.text(
                f"""UPDATE {table} SET numero=0 WHERE numero is NULL;
            """
            )
        )
        session.commit()
        op.alter_column(table, "numero", existing_type=sa.INTEGER(), nullable=False)


def downgrade():
    #
    op.add_column(
        "notes_ue",
        sa.Column("parcour_id", sa.INTEGER(), autoincrement=False, nullable=True),
    )
    op.drop_table("ue_parcours")
    for table in (
        "apc_competence",
        "apc_parcours",
        "notes_form_modalites",
        "notes_ue",
        "notes_matieres",
        "notes_modules",
        "notes_evaluation",
        "partition",
        "group_descr",
    ):
        op.alter_column(table, "numero", existing_type=sa.INTEGER(), nullable=True)
