# src/fmatch/saas/auth/__init__.py
"""
Auth package - authentication and authorization utilities.
"""

# Import from auth_core (the renamed auth.py)
from ..auth_core import get_current_account, require_admin

# Import from users module
from .users import get_current_user

# Backward-compatible dependency: verify_api_key
# Some v1 routes import `verify_api_key` from fmatch.saas.auth.
# Provide a thin wrapper around the newer v1 deps implementation so older
# endpoints continue to work without changing imports.
from typing import Optional
from fastapi import Depends, Header, Request, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from ..db import get_session


async def verify_api_key(
    request: Request,
    authorization: Optional[str] = Header(default=None, alias="Authorization"),
    x_api_key: Optional[str] = Header(default=None, alias="X-API-Key"),
    db: AsyncSession = Depends(get_session),
) -> str:
    """Compatibility wrapper that validates API key and returns a string.

    Delegates to api.v1.deps.require_api_key which performs full validation,
    rate limiting hints, and attaches context to request.state. Returns the
    API key prefix as a simple string to match legacy signatures where the
    actual value is not used by the handler.
    """
    try:
        from ..api.v1.deps import require_api_key as _require_api_key

        ctx = await _require_api_key(
            request=request,
            authorization=authorization,
            x_api_key=x_api_key,
            db=db,
        )
        return getattr(ctx, "api_key_prefix", "ok")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=401, detail=f"API key verification failed: {e}")


__all__ = [
    "get_current_account",
    "require_admin",
    "get_current_user",
    "verify_api_key",
]
