from typing import Optional
from core.exceptions import ConflictError
from infrastructure.redis.client import get_redis_client


class IdempotencyManager:
    """Ensures requests with Idempotency-Key are not executed twice."""

    @staticmethod
    async def acquire_or_raise(
        key: str,
        tenant_id: Optional[str] = None,
        expire_seconds: int = 86400,
    ) -> bool:
        redis = await get_redis_client()
        redis_key = f"idempotency:{tenant_id or 'global'}:{key}"
        # SET NX EX
        acquired = await redis.set(redis_key, "IN_PROGRESS", nx=True, ex=expire_seconds)
        if not acquired:
            raise ConflictError("Request already submitted or processed (Idempotency conflict)")
        return True

    @staticmethod
    async def mark_completed(
        key: str,
        tenant_id: Optional[str] = None,
        result_payload: Optional[str] = "COMPLETED",
        expire_seconds: int = 86400,
    ) -> None:
        redis = await get_redis_client()
        redis_key = f"idempotency:{tenant_id or 'global'}:{key}"
        await redis.set(redis_key, result_payload or "COMPLETED", ex=expire_seconds)
