"""Database initialization module.""" import logging from sqlalchemy.orm import Session from app.core.config import settings from app.core.security import get_password_hash from app.models.user import User from app.schemas.user import UserCreate logger = logging.getLogger(__name__) def init_db(db: Session) -> None: """Initialize database with initial data.""" # Check if there are any users in the database user = db.query(User).first() if user: logger.info("Database already initialized, skipping") return # Create first superuser if environment variables are set if settings.FIRST_SUPERUSER_EMAIL and settings.FIRST_SUPERUSER_PASSWORD: logger.info("Creating initial superuser") user_in = UserCreate( email=settings.FIRST_SUPERUSER_EMAIL, password=settings.FIRST_SUPERUSER_PASSWORD, full_name="Initial Superuser", is_superuser=True, ) db_user = User( email=user_in.email, hashed_password=get_password_hash(user_in.password), full_name=user_in.full_name, is_superuser=user_in.is_superuser, is_active=True, ) db.add(db_user) db.commit() logger.info(f"Superuser {settings.FIRST_SUPERUSER_EMAIL} created")