# retoor <retoor@molodetz.nl>

import requests

from tests.conftest import BASE_URL
from tests.api.admin.gateway.index import (
    JSON_gateway,
    admin_session,
    member_key,
    _unique_gateway,
)


def test_providers_require_admin(seeded_db):
    assert (
        requests.get(
            f"{BASE_URL}/admin/gateway/providers",
            headers=JSON_gateway,
            allow_redirects=False,
        ).status_code
        == 401
    )
    key = member_key()
    assert (
        requests.get(
            f"{BASE_URL}/admin/gateway/providers",
            headers={**JSON_gateway, "X-API-KEY": key},
            allow_redirects=False,
        ).status_code
        == 403
    )
    assert (
        admin_session(seeded_db)
        .get(f"{BASE_URL}/admin/gateway/providers")
        .status_code
        == 200
    )


def test_provider_create_update_delete(seeded_db):
    admin = admin_session(seeded_db)
    name = _unique_gateway("prov").lower()

    created = admin.post(
        f"{BASE_URL}/admin/gateway/providers",
        json={
            "name": name,
            "base_url": "https://x.example/v1/chat/completions",
            "api_key": "sk-x",
            "is_active": True,
        },
    )
    assert created.status_code == 200, created.text[:300]
    assert created.json()["ok"] is True

    listed = admin.get(f"{BASE_URL}/admin/gateway/providers").json()
    match = next((p for p in listed["providers"] if p["name"] == name), None)
    assert match is not None
    assert match["base_url"] == "https://x.example/v1/chat/completions"

    updated = admin.post(
        f"{BASE_URL}/admin/gateway/providers",
        json={"name": name, "base_url": "https://y.example/v1/chat/completions"},
    )
    assert updated.status_code == 200
    relisted = admin.get(f"{BASE_URL}/admin/gateway/providers").json()
    match = next(p for p in relisted["providers"] if p["name"] == name)
    assert match["base_url"] == "https://y.example/v1/chat/completions"

    deleted = admin.delete(f"{BASE_URL}/admin/gateway/providers/{name}")
    assert deleted.status_code == 200 and deleted.json()["ok"] is True
    assert (
        admin.delete(f"{BASE_URL}/admin/gateway/providers/{name}").status_code == 404
    )


def test_provider_name_validation(seeded_db):
    admin = admin_session(seeded_db)
    bad = admin.post(
        f"{BASE_URL}/admin/gateway/providers",
        json={"name": "has spaces!", "base_url": "https://z.example/v1/chat/completions"},
    )
    assert bad.status_code == 400
    assert bad.json()["ok"] is False
