import logging
from fastapi import APIRouter, Body
from common.message_limit import message_limit_service

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/api/limit", tags=["Limit Management"])

@router.get("/info", summary="Lấy thông tin limit của 1 ID (vd: device:xxx hoặc user:yyy)")
async def get_limit_info(identity_key: str):
    """
    identity_key format: 'device:id' hoặc 'user:id'
    """
    is_authenticated = identity_key.startswith("user:")
    info = await message_limit_service.get_usage(identity_key, is_authenticated)
    return {"status": "success", "info": info}

@router.post("/reset", summary="Reset limit (thêm limit / cho phép nhắn lại) cho 1 ID")
async def reset_limit(payload: dict = Body(...)):
    identity_key = payload.get("identity_key")
    if not identity_key:
        return {"status": "error", "message": "Missing identity_key"}
        
    success = await message_limit_service.reset(identity_key)
    if success:
        return {"status": "success", "message": f"Đã reset/thêm limit cho {identity_key} (về 0)"}
    else:
        return {"status": "error", "message": "Có lỗi khi reset limit"}
