# retoor <retoor@molodetz.nl>

import time
import pytest
import requests
from tests.conftest import BASE_URL
from devplacepy.database import get_table, refresh_snapshot, set_setting

_counter_uu = [0]


@pytest.fixture(scope="module", autouse=True)
def _upload_settings(app_server):
    for key, value in {
        "rate_limit_per_minute": "1000000",
        "rate_limit_window_seconds": "60",
        "registration_open": "1",
        "maintenance_mode": "0",
        "max_upload_size_mb": "10",
        "allowed_file_types": "",
    }.items():
        set_setting(key, value)
    yield


def _key():
    _counter_uu[0] += 1
    name = f"uu{int(time.time() * 1000)}{_counter_uu[0]}"
    requests.post(
        f"{BASE_URL}/auth/signup",
        data={
            "username": name,
            "email": f"{name}@t.dev",
            "password": "secret123",
            "confirm_password": "secret123",
            "birth_date": "1990-01-01",
            "accept_terms": "1",
        },
        allow_redirects=True,
    )
    refresh_snapshot()
    return get_table("users").find_one(username=name)["api_key"]


def _post(url, key, filename=None):
    headers = {"X-API-KEY": key} if key else {}
    data = {"url": url}
    if filename:
        data["filename"] = filename
    return requests.post(f"{BASE_URL}/uploads/upload-url", headers=headers, data=data)


def test_upload_url_requires_auth(app_server):
    r = _post("http://example.com/x.png", None)
    assert r.status_code == 401


def test_upload_url_invalid_key(app_server):
    r = _post("http://example.com/x.png", "not-a-real-key")
    assert r.status_code == 401


def test_upload_url_empty_url_validation(app_server):
    r = requests.post(
        f"{BASE_URL}/uploads/upload-url",
        headers={"X-API-KEY": _key(), "Accept": "application/json"},
        data={"url": ""},
    )
    assert r.status_code == 422


def test_upload_url_rejects_loopback_ssrf(app_server):
    r = _post("http://127.0.0.1/payload.png", _key())
    assert r.status_code == 400
    assert "private or local" in r.json()["error"].lower()


def test_upload_url_rejects_private_range_ssrf(app_server):
    r = _post("http://10.0.0.1/payload.png", _key())
    assert r.status_code == 400
    assert "private or local" in r.json()["error"].lower()


def test_upload_url_rejects_non_http_scheme(app_server):
    r = _post("ftp://example.com/payload.png", _key())
    assert r.status_code == 400
    assert "http" in r.json()["error"].lower()


def test_upload_url_unresolvable_host(app_server):
    r = _post("http://nonexistent.invalid.zzz/payload.png", _key())
    assert r.status_code == 400
    assert "resolve" in r.json()["error"].lower()
