import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlmodel import SQLModel

import backend.app.db.models.magic_plan  # noqa: F401 — registers MagicPlan models with SQLModel.metadata

# TODO: promote to backend/app/db/conftest.py once a second DB-touching test directory appears under this tree


@pytest.fixture(scope="function")
def engine(postgresql):
    connection_string = (
        f"postgresql+psycopg://"
        f"{postgresql.info.user}:"
        f"{postgresql.info.password}@"
        f"{postgresql.info.host}:"
        f"{postgresql.info.port}/"
        f"{postgresql.info.dbname}"
    )

    engine = create_engine(connection_string)
    SQLModel.metadata.create_all(engine)

    yield engine

    SQLModel.metadata.drop_all(engine)
    engine.dispose()


@pytest.fixture(scope="function")
def db_session(engine):
    connection = engine.connect()
    transaction = connection.begin()
    session = sessionmaker(bind=connection)()

    yield session

    session.close()
    transaction.rollback()
    connection.close()
