from contextlib import asynccontextmanager
from typing import AsyncGenerator, Optional
from core.exceptions import ConflictError
from infrastructure.redis.client import get_redis_client


@asynccontextmanager
async def distributed_lock(
    resource_name: str,
    timeout_seconds: float = 10.0,
    blocking_timeout: float = 2.0,
    tenant_id: Optional[str] = None,
) -> AsyncGenerator[None, None]:
    """Acquires a distributed lock using Redis."""
    redis = await get_redis_client()
    lock_key = f"lock:{tenant_id or 'global'}:{resource_name}"
    lock = redis.lock(
        lock_key,
        timeout=timeout_seconds,
        blocking_timeout=blocking_timeout,
    )

    acquired = await lock.acquire()
    if not acquired:
        raise ConflictError(f"Resource {resource_name} is locked by another operation")

    try:
        yield
    finally:
        try:
            await lock.release()
        except Exception:
            pass
