import logging
import requests
import urllib.parse
from typing import Optional

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

class UrlService:
    def __init__(self):
        pass

    def shorten_url(self, long_url: str, api_url: str, is_persist: bool = False) -> Optional[str]:
        """
        Shorten a URL by calling the external urlshortener API.

        :param long_url: the original long URL to shorten
        :param api_url: base API URL (e.g. "https://example.com/api/")
        :param is_persist: whether to persist the shortened URL on the service
        :return: shortUrlCode on success, or an empty string / None on failure
        """
        try:
            short_url = ""

            headers = {"Content-Type": "application/json"}

            encoded = urllib.parse.quote(long_url, safe="")
            payload = {"longUrl": encoded, "isPersist": is_persist}

            post_url = f"{api_url.rstrip('/')}/urlshortener"
            resp = requests.post(post_url, json=payload, headers=headers, timeout=10)

            if resp is not None and resp.status_code == 201:
                data = resp.json()
                short_url = data.get("shortUrlCode", "")
            else:
                logger.warning(
                    "Shorten URL request returned status %s: %s",
                    getattr(resp, "status_code", None),
                    getattr(resp, "text", None),
                )

            return short_url
        except Exception as exc:  # keep broad to mirror original behaviour
            logger.exception("error occurred while shortening url - %s", long_url)
            return None
