"""validation niveaux inferieurs

Revision ID: c701224fa255
Revises: d84bc592584e
Create Date: 2023-06-11 11:08:05.553898

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

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

Session = sessionmaker()


def upgrade():
    # Ajoute la colonne formation_id, nullable, la peuple puis la rend non nullable
    op.add_column(
        "apc_validation_annee", sa.Column("formation_id", sa.Integer(), nullable=True)
    )
    op.create_foreign_key(
        "apc_validation_annee_formation_id_fkey",
        "apc_validation_annee",
        "notes_formations",
        ["formation_id"],
        ["id"],
    )

    # Affecte la formation des anciennes validations
    bind = op.get_bind()
    session = Session(bind=bind)
    session.execute(
        sa.text(
            """
        UPDATE apc_validation_annee AS a
        SET formation_id = (
            SELECT f.id
            FROM notes_formations f
            JOIN notes_formsemestre s ON f.id = s.formation_id
            WHERE s.id = a.formsemestre_id
        )
        WHERE a.formsemestre_id IS NOT NULL;
        """
        )
    )
    op.alter_column(
        "apc_validation_annee",
        "formation_id",
        nullable=False,
    )


def downgrade():
    with op.batch_alter_table("apc_validation_annee", schema=None) as batch_op:
        batch_op.drop_constraint(
            "apc_validation_annee_formation_id_fkey", type_="foreignkey"
        )
        batch_op.drop_column("formation_id")
