"""Redis-backed limits for public auth email requests."""
from __future__ import annotations

import hashlib
from typing import Optional

from redis import asyncio as aioredis

from src.core.exceptions import RateLimitError


async def enforce_auth_email_limits(redis: aioredis.Redis, *, email: str, ip_address: Optional[str]) -> None:
    """Allow one send per email per five minutes and ten requests per IP per hour."""
    email_key = f"p2hs:auth-email:{hashlib.sha256(email.lower().encode()).hexdigest()}"
    email_count = await redis.incr(email_key)
    if email_count == 1:
        await redis.expire(email_key, 300)
    if email_count > 1:
        raise RateLimitError("Please wait five minutes before requesting another email.")
    if ip_address:
        ip_key = f"p2hs:auth-ip:{hashlib.sha256(ip_address.encode()).hexdigest()}"
        ip_count = await redis.incr(ip_key)
        if ip_count == 1:
            await redis.expire(ip_key, 3600)
        if ip_count > 10:
            raise RateLimitError("Too many authentication requests. Please try again later.")
