"""Login do painel (multi-usuário, guardado no banco)."""
import hashlib
import secrets

from sqlalchemy.orm import Session

from .models import User

DEFAULT_USERNAME = "admin"
DEFAULT_PASSWORD = "admin"


def _hash_password(password: str, salt: bytes | None = None):
    salt = salt or secrets.token_bytes(16)
    digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, 200_000)
    return salt.hex(), digest.hex()


def seed_default_user(db: Session):
    if db.query(User).count() > 0:
        return
    salt_hex, hash_hex = _hash_password(DEFAULT_PASSWORD)
    db.add(User(username=DEFAULT_USERNAME, password_hash=hash_hex, salt=salt_hex))
    db.commit()


def create_user(db: Session, username: str, password: str):
    salt_hex, hash_hex = _hash_password(password)
    db.add(User(username=username, password_hash=hash_hex, salt=salt_hex))
    db.commit()


def change_password(db: Session, user_id: int, new_password: str):
    user = db.get(User, user_id)
    salt_hex, hash_hex = _hash_password(new_password)
    user.salt = salt_hex
    user.password_hash = hash_hex
    db.commit()


def delete_user(db: Session, user_id: int):
    user = db.get(User, user_id)
    if user is not None:
        db.delete(user)
        db.commit()


def verify_user(db: Session, username: str, password: str) -> bool:
    user = db.query(User).filter_by(username=username).first()
    if user is None:
        return False
    _, hash_hex = _hash_password(password, bytes.fromhex(user.salt))
    return secrets.compare_digest(hash_hex, user.password_hash)
