from app.core.media_signing import build_signed_media_url, verify_signed_media
from app.core.config import settings
import time


def test_build_and_verify_signed_media_url():
    signed = build_signed_media_url("/api/v1/media/files/avatars/user/file.png")
    assert signed is not None
    assert "expires=" in signed
    assert "sig=" in signed

    path = "avatars/user/file.png"
    query = signed.split("?", 1)[1]
    params = dict(part.split("=") for part in query.split("&"))
    assert int(params["expires"]) - int(time.time()) <= settings.media_url_ttl_seconds
    assert verify_signed_media(path, int(params["expires"]), params["sig"])


def test_build_signed_media_url_none():
    assert build_signed_media_url(None) is None


def test_verify_signed_media_rejects_expired_signature():
    signed = build_signed_media_url("/api/v1/media/files/avatars/user/file.png")
    assert signed is not None
    path = "avatars/user/file.png"
    query = signed.split("?", 1)[1]
    params = dict(part.split("=") for part in query.split("&"))
    assert not verify_signed_media(path, int(params["expires"]) - 10_000, params["sig"])


def test_verify_signed_media_rejects_tampered_signature():
    signed = build_signed_media_url("/api/v1/media/files/avatars/user/file.png")
    assert signed is not None
    path = "avatars/user/file.png"
    query = signed.split("?", 1)[1]
    params = dict(part.split("=") for part in query.split("&"))
    assert not verify_signed_media(path, int(params["expires"]), "invalid")
