import logging

from sqlalchemy.orm import Session
from sqlalchemy import select

from app.core.config import settings
from app.core.security import get_password_hash
from app.db.base_class import Base
from app.db.session import engine
from app.db.models import User

logger = logging.getLogger(__name__)

def init_db(db: Session) -> None:
    # MVP: create tables if they don't exist
    Base.metadata.create_all(bind=engine)
    
    bootstrap_admin(db)

def bootstrap_admin(db: Session) -> None:
    admin_login = settings.admin_bootstrap_login
    admin_pass = settings.admin_bootstrap_password
    
    user = db.scalar(select(User).where(User.login == admin_login))
    if not user:
        logger.info(f"Creating bootstrap admin user: {admin_login}")
        hashed_password = get_password_hash(admin_pass)
        admin_user = User(
            login=admin_login,
            hashed_password=hashed_password,
            is_active=True,
        )
        db.add(admin_user)
        db.commit()
        db.refresh(admin_user)
    else:
        logger.info(f"Admin user {admin_login} already exists")
