"""x-api-key authentication for the recruitment endpoints."""
import secrets
from typing import Optional

from fastapi import HTTPException, Security
from fastapi.security import APIKeyHeader

from recruitment import config

# auto_error=False so a missing header gets our own 401 instead of FastAPI's 403.
_api_key_header = APIKeyHeader(name="x-api-key", auto_error=False)


async def verify_api_key(api_key: Optional[str] = Security(_api_key_header)) -> None:
    expected = config.API_KEY
    if not expected:
        # Fail closed: an unconfigured server must never accept every caller.
        raise HTTPException(status_code=500, detail="Recruitment API key is not configured")
    # Constant-time comparison so the key can't be recovered by timing.
    if not api_key or not secrets.compare_digest(api_key.encode(), expected.encode()):
        raise HTTPException(status_code=401, detail="Invalid or missing x-api-key")
