"""Admin auth middleware — require_admin() dependency.

Founder-only route guard. Checks Firestore ``admins`` collection
keyed by SHA-256 of the lowercase email. Returns ``None`` to
continue, or a 404 response to hide the route from non-admins.
"""

from __future__ import annotations

import hashlib
import logging
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from fastapi import Request

_log = logging.getLogger(__name__)


async def require_admin(request: Request) -> None:
    """Founder-only route guard (FastAPI dependency).

    1. Read ``customer_email`` from the resolved
       ``CustomerContext`` on ``request.state``.
    2. Hash with SHA-256 and look up ``admins/{hash}``.
    3. If NOT found → raise 404 (hides route existence).
    4. If found → return ``None`` (allow request through).

    Firestore ``admins`` collection schema::

        admins/{sha256(email.lower())}/
            email: str
            added_at: ISO 8601
            added_by: str
    """
    from backend.dashboard.middleware import (
        DashboardAuthError,
        require_dashboard_auth,
    )
    from backend.shared.firestore import get_db

    try:
        ctx = await require_dashboard_auth(request)
    except DashboardAuthError as exc:
        raise _not_found() from exc

    email = ctx.email.lower().strip()
    email_hash = hashlib.sha256(email.encode()).hexdigest()

    db = get_db()
    doc = await db.collection("admins").document(email_hash).get()
    if not doc.exists:
        _log.debug("Admin check failed for %s", email_hash[:8])
        raise _not_found()

    # Store context for downstream route handlers
    request.state.admin_email = email
    request.state.customer_context = ctx


def _not_found() -> Exception:
    """Return an HTTP 404 to hide route from non-admins."""
    from fastapi import HTTPException

    return HTTPException(status_code=404, detail="Not Found")
