import uuid
from unittest.mock import MagicMock

from app.routers.images import _image_to_dict


def _make_image(*, thumbnail_key=None):
    img = MagicMock()
    img.id = uuid.UUID("00000000-0000-0000-0000-000000000001")
    img.short_id = "AbCd1234"
    img.hash = "abc123"
    img.filename = "test.jpg"
    img.mime_type = "image/jpeg"
    img.size_bytes = 1024
    img.width = 100
    img.height = 100
    img.storage_key = "abc123storagekey"
    img.thumbnail_key = thumbnail_key
    img.created_at.isoformat.return_value = "2026-05-09T00:00:00"
    img.tags = []
    return img


def test_cdn_configured_with_thumbnail():
    img = _make_image(thumbnail_key="abc123storagekey-thumb")
    result = _image_to_dict(img, cdn_base="https://cdn.example.com")
    assert result["file_url"] == "https://cdn.example.com/abc123storagekey"
    assert result["thumbnail_url"] == "https://cdn.example.com/abc123storagekey-thumb"
    assert result["short_id"] == "AbCd1234"


def test_cdn_configured_no_thumbnail():
    img = _make_image(thumbnail_key=None)
    result = _image_to_dict(img, cdn_base="https://cdn.example.com")
    assert result["file_url"] == "https://cdn.example.com/abc123storagekey"
    assert result["thumbnail_url"] is None
    assert result["short_id"] == "AbCd1234"


def test_no_cdn_with_thumbnail():
    img = _make_image(thumbnail_key="abc123storagekey-thumb")
    result = _image_to_dict(img, cdn_base=None)
    assert result["file_url"] == "/api/v1/i/AbCd1234/file"
    assert result["thumbnail_url"] == "/api/v1/i/AbCd1234/thumbnail"


def test_no_cdn_no_thumbnail():
    img = _make_image(thumbnail_key=None)
    result = _image_to_dict(img, cdn_base=None)
    assert result["file_url"] == "/api/v1/i/AbCd1234/file"
    assert result["thumbnail_url"] is None


def test_cdn_trailing_slash_normalised():
    img = _make_image(thumbnail_key="abc123storagekey-thumb")
    result = _image_to_dict(img, cdn_base="https://cdn.example.com/")
    assert result["file_url"] == "https://cdn.example.com/abc123storagekey"
    assert result["thumbnail_url"] == "https://cdn.example.com/abc123storagekey-thumb"
    assert "//" not in result["file_url"].replace("https://", "")


def test_cdn_trailing_whitespace_normalised():
    img = _make_image(thumbnail_key="abc123storagekey-thumb")
    result = _image_to_dict(img, cdn_base="https://cdn.example.com  ")
    assert result["file_url"] == "https://cdn.example.com/abc123storagekey"
    assert result["thumbnail_url"] == "https://cdn.example.com/abc123storagekey-thumb"


def test_short_id_in_response():
    img = _make_image()
    result = _image_to_dict(img, cdn_base=None)
    assert result["short_id"] == "AbCd1234"
