import hashlib
import hmac
import secrets
from datetime import datetime, timedelta, timezone

from app.core.config import settings


VERIFICATION_CODE_EXPIRE_MINUTES = 10


def generate_verification_code() -> str:
    return f"{secrets.randbelow(1_000_000):06d}"


def hash_verification_code(code: str) -> str:
    return hmac.new(
        settings.JWT_SECRET.encode("utf-8"),
        code.encode("utf-8"),
        hashlib.sha256,
    ).hexdigest()


def verify_verification_code(
    code: str,
    code_hash: str,
) -> bool:
    expected_hash = hash_verification_code(code)

    return hmac.compare_digest(
        expected_hash,
        code_hash,
    )


def verification_expiry() -> datetime:
    return datetime.now(timezone.utc) + timedelta(
        minutes=VERIFICATION_CODE_EXPIRE_MINUTES
    )