import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# In Docker, we pass PLATFORM_DB_URL or use env vars
pg_user = os.getenv("PLATFORM_DB_USER", "user-database-user")
pg_pass = os.getenv("PLATFORM_DB_PASSWORD", "password123")
pg_db   = os.getenv("PLATFORM_DB_NAME", "user-database")
pg_host = os.getenv("PLATFORM_DB_HOST", "platform_db") # Container name in compose
pg_port = os.getenv("PLATFORM_DB_PORT", "5432")

default_url = f"postgresql://{pg_user}:{pg_pass}@{pg_host}:{pg_port}/{pg_db}"
DB_URL = os.getenv("PLATFORM_DB_URL", default_url)

engine = create_engine(DB_URL, pool_pre_ping=True)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
