"""
Shared database and cache helpers used by webhook infrastructure and APIs.
"""

from __future__ import annotations

from typing import AsyncGenerator

import redis.asyncio as redis
from sqlalchemy.ext.asyncio import AsyncSession

from . import settings
from contextlib import asynccontextmanager
from .db import AsyncSessionLocal


async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
    """FastAPI dependency and utility to yield an async DB session.

    Mirrors the pattern used elsewhere but provided here so webhook modules
    can import a stable path (fmatch.saas.database).
    """
    async with AsyncSessionLocal() as session:
        yield session


def get_redis_client() -> redis.Redis:
    """FastAPI dependency to provide an asyncio Redis client.

    Returns a configured redis.asyncio Redis instance.
    """
    return redis.from_url(settings.REDIS_URL, encoding="utf-8", decode_responses=True)


@asynccontextmanager
async def session_context() -> AsyncGenerator[AsyncSession, None]:
    """Async context manager for DB sessions (for non-FastAPI call-sites)."""
    async with AsyncSessionLocal() as session:
        yield session
