"""Live (uncached) reads about login accounts, for the CRM session guard and the account-creation / password routes.

Kept apart from agent_queries.py, whose function bodies are frozen by the Website split contract
(tests/website/test_catalog_split_contract.py) and whose reads are cached; these must never be cached.
"""
from modules.classes import DatabaseConnectionManager


def get_agent_session_state(agent_id):
    """dict(is_active, access_level, password_hash) of one agent, or None when the row is gone.

    Read on every authenticated CRM request: role changes, deactivation and password changes have to take effect on the
    next request in every worker.
    """
    with DatabaseConnectionManager("agents") as conn:
        row = conn.cursor().execute(
            "SELECT is_active, access_level, password_hash FROM agents_v2 WHERE id = ?", (agent_id,)
        ).fetchone()
    if row is None:
        return None
    return {"is_active": row[0], "access_level": row[1], "password_hash": row[2]}


def login_exists(login):
    """True when an account with this login exists, ignoring case. (The UNIQUE index on `login` stays the final arbiter.)"""
    with DatabaseConnectionManager("agents") as conn:
        return conn.cursor().execute("SELECT 1 FROM agents_v2 WHERE lower(login) = lower(?)", (login,)).fetchone() is not None


def get_agent_identity(agent_id):
    """Identity data of one agent for the password policy (login, names, contact data), or None when the row is gone."""
    with DatabaseConnectionManager("agents") as conn:
        row = conn.cursor().execute(
            "SELECT login, first_name, last_name, email, phone, license FROM agents_v2 WHERE id = ?", (agent_id,)
        ).fetchone()
    if row is None:
        return None
    return {"login": row[0], "first_name": row[1], "last_name": row[2], "email": row[3], "phone": row[4], "licence": row[5]}
