"""The WordPress companion installer is off unless explicitly enabled (server-side kill switch)."""

from __future__ import annotations

from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock

import pytest
from src.core.exceptions import ForbiddenError
from src.domain.external_admin import router as router_module
from src.domain.external_admin import service as service_module
from src.domain.external_admin.schemas import CompanionInstallRequest
from src.domain.external_admin.service import ExternalAdminService


def _settings(enabled: bool):
    return SimpleNamespace(wp_companion_install_enabled=enabled)


def _service():
    others = [MagicMock() for _ in range(11)]
    return ExternalAdminService(*others)


def test_it_is_off_by_default():
    from src.config import Settings

    assert Settings().wp_companion_install_enabled is False


async def test_install_is_refused_before_touching_the_installation(monkeypatch):
    monkeypatch.setattr(service_module, "get_settings", lambda: _settings(False))
    svc = _service()
    svc._resolve_wordpress_installation_for_chat = AsyncMock()
    svc._check_companion_update = AsyncMock()

    with pytest.raises(ForbiddenError, match="companion_install_disabled"):
        await svc.handle_wordpress_companion_install(
            "token", CompanionInstallRequest(installation_id="abc", requested_version="1.0.0")
        )
    svc._resolve_wordpress_installation_for_chat.assert_not_awaited()
    svc._check_companion_update.assert_not_awaited()


async def test_install_works_when_explicitly_enabled(monkeypatch):
    monkeypatch.setattr(service_module, "get_settings", lambda: _settings(True))
    svc = _service()
    svc._resolve_wordpress_installation_for_chat = AsyncMock(return_value=MagicMock())
    svc._check_companion_update = AsyncMock(
        return_value={
            "url": "https://x/p.zip",
            "signature": "sig",
            "version": "1.0.0",
            "sha256": "ab",
        }
    )
    out = await svc.handle_wordpress_companion_install(
        "token", CompanionInstallRequest(installation_id="abc", requested_version="1.0.0")
    )
    assert out.download_url == "https://x/p.zip"


async def test_package_download_is_refused_when_disabled(monkeypatch):
    monkeypatch.setattr(router_module, "get_app_settings", lambda: _settings(False))
    resolver = MagicMock()
    monkeypatch.setattr(router_module, "resolve_wordpress_companion_package", resolver)

    with pytest.raises(ForbiddenError, match="companion_install_disabled"):
        await router_module.companion_package_download(version="1.0.0", _gateway=None)
    resolver.assert_not_called()  # never even looks for the file
