"""
Configuration de la base de données TIM CASH (PostgreSQL)
"""
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import os
from dotenv import load_dotenv
from core.config import settings

# Charger les variables d'environnement
load_dotenv()

# Exemple d’URL PostgreSQL :
# postgresql+psycopg2://user:password@localhost:5432/timcash_db
# DATABASE_URL = os.getenv(
#     "DATABASE_URL",
#     "postgresql+psycopg2://timcash:timcash123@localhost:5432/timcash_db"
# )
DATABASE_URL = settings.DATABASE_URL


# Configuration PostgreSQL (plus stricte sur la gestion du pool)
pg_config = {
    "pool_size": 10,
    "max_overflow": 20,
    "pool_pre_ping": True,
    "pool_recycle": 3600,
    "echo": os.getenv("DEBUG", "false").lower() == "true"
}

# Création du moteur selon le type de base
if "postgresql" in DATABASE_URL:
    engine = create_engine(DATABASE_URL, **pg_config)
elif "sqlite" in DATABASE_URL:
    engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
else:
    engine = create_engine(DATABASE_URL)

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

# Base de modèles
Base = declarative_base()

# Métadonnées (pour Alembic)
metadata = MetaData()

def get_db():
    """
    Générateur de session de base de données
    """
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

def create_tables():
    """
    Créer toutes les tables
    """
    Base.metadata.create_all(bind=engine)

def drop_tables():
    """
    Supprimer toutes les tables
    """
    Base.metadata.drop_all(bind=engine)
