"""Database engine and session setup.

Defaults to a local SQLite file for the demo. To switch to Postgres/MySQL/SQL Server,
set DATABASE_URL in .env (e.g. 'postgresql://user:pass@host/db' or
'mssql+pyodbc://user:pass@host/db?driver=ODBC+Driver+17+for+SQL+Server')."""
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base, sessionmaker

DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./devops_tickets.db")

# check_same_thread is a SQLite-only quirk for FastAPI's threaded request handling
connect_args = {"check_same_thread": False} if DATABASE_URL.startswith("sqlite") else {}

engine = create_engine(DATABASE_URL, connect_args=connect_args)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()


def get_db():
    """FastAPI dependency — yields a DB session and closes it after the request."""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
