from contextlib import contextmanager
from typing import Generator

from sqlalchemy import create_engine
from sqlalchemy.engine import URL
from sqlalchemy.orm import Session, declarative_base, sessionmaker

from app.config import settings


Base = declarative_base()


def _build_mysql_url(database: str | None = None) -> URL:
	return URL.create(
		drivername='mysql+pymysql',
		username=settings.mysql_user,
		password=settings.mysql_password,
		host=settings.mysql_host,
		port=settings.mysql_port,
		database=database,
	)


engine = create_engine(
	_build_mysql_url(settings.mysql_database),
	pool_pre_ping=True,
	pool_recycle=3600,
)

SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, class_=Session)


@contextmanager
def db_session() -> Generator[Session, None, None]:
	session = SessionLocal()
	try:
		yield session
	finally:
		session.close()
