import json
import uuid
from urllib.request import Request, urlopen
from urllib.error import URLError
from typing import Optional, Dict, Any


def authorize(
    api_key: str,
    token: str,
    method: str,
    path: str,
    request_id: Optional[str] = None,
    base_url: str = "https://api.payfence.io",
) -> Dict[str, Any]:
    """Call PayFence authorize endpoint. Returns decision dict."""
    url = f"{base_url.rstrip('/')}/v1/authorize"
    payload = json.dumps({
        "token": token,
        "method": method,
        "path": path,
        "requestId": request_id or str(uuid.uuid4()),
    }).encode()

    req = Request(url, data=payload, method="POST")
    req.add_header("Content-Type", "application/json")
    req.add_header("Authorization", f"Bearer {api_key}")

    with urlopen(req, timeout=10) as resp:
        return json.loads(resp.read())
