"""Introduce schema field to Boefje model

Revision ID: 5be152459a7b
Revises: f9de6eb7824b
Create Date: 2024-08-08 14:47:12.582017

"""

import logging

import sqlalchemy as sa
from alembic import op
from sqlalchemy import text

from boefjes.local_repository import get_local_repository

# revision identifiers, used by Alembic.
revision = "5be152459a7b"
down_revision = "f9de6eb7824b"
branch_labels = None
depends_on = None

logger = logging.getLogger(__name__)


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column("boefje", sa.Column("schema", sa.JSON(), nullable=True))

    local_repo = get_local_repository()
    connection = op.get_bind()

    with connection.begin():
        plugins = local_repo.get_all()
        logger.info("Found %s plugins", len(plugins))

        for plugin in local_repo.get_all():
            schema = local_repo.schema(plugin.id)
            if schema:
                query = text("UPDATE boefje SET schema = :schema WHERE plugin_id = :plugin_id")  # noqa: S608
                connection.execute(query, {"schema": schema, "plugin_id": plugin.id})
                logger.info("Updated any database entries for plugin %s", plugin.id)
            else:
                logger.info("No schema present for plugin %s", plugin.id)

    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("boefje", "schema")
    # ### end Alembic commands ###
