import os
from dotenv import load_dotenv
from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base, sessionmaker

load_dotenv()
DB_USER = os.getenv("DB_USER", 'default_user')
DB_PASSWORD = os.getenv("DB_PASSWORD", 'default_password')
DB_HOST = os.getenv("DB_HOST", "default_host")
DB_PORT = os.getenv("DB_PORT", "default_port")
DB_NAME = os.getenv("DB_NAME", "default_name")
DB_ENGINE = os.getenv("DB_ENGINE", "postgresql")

DB_URI = f'{DB_ENGINE}://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}'

engine = create_engine(DB_URI)

# all models should inherit this
Base = declarative_base()

# handles db sessions
Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)

def get_db():
    db = Session()

    try:
        yield db
    except:
        Exception("error getting db session")
    
    finally:
        db.close()
