"""Monkey-patch DRF fields to always produce absolute media URLs."""

from django.conf import settings
from rest_framework import serializers


def _absolute_file_url(self, value):
    """Return absolute URL for file fields, even without request in context."""
    if not value:
        return None

    try:
        url = value.url
    except Exception:
        return None

    # If already absolute, return as-is
    if url.startswith("http://") or url.startswith("https://"):
        return url

    # Try using request from context
    request = self.context.get("request")
    if request:
        return request.build_absolute_uri(url)

    # Fallback to SITE_URL setting
    site_url = getattr(settings, "SITE_URL", "").rstrip("/")
    if site_url:
        return f"{site_url}{url}"

    return url


def patch_drf_file_fields():
    """Override to_representation on FileField and ImageField globally."""
    serializers.FileField.to_representation = _absolute_file_url
    serializers.ImageField.to_representation = _absolute_file_url
