from contextlib import contextmanager
from pathlib import Path

from pydantic_settings import BaseSettings, SettingsConfigDict
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session

BASE_PATH = Path(__file__).parent.parent.absolute()


class Settings(BaseSettings):
    database_url: str
    product_key: str
    stripe_secret_key: str
    stripe_public_key: str
    stripe_success_url:str
    stripe_cancel_url:str
    stripe_webhook_url:str
    reset_password_token_time_out: int=3
    app_base_url: str = "http://localhost:8000"
    model_config = SettingsConfigDict(env_file=str(BASE_PATH / '.env'), env_file_encoding='utf-8')


settings = Settings()
engine = create_engine(settings.database_url)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


@contextmanager
def get_db() -> Session:
    """Dependency for creating a session with context management."""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
