"""
T-API: Demo Config API endpoint verification.

Tests the admin API endpoints for listing, loading, and removing demo configs.
Uses FastAPI TestClient (no running server needed).

Note: Login requires CSRF + form-data + httpOnly cookies, so we test
unauthenticated rejection and the discovery module directly.
"""

import pytest


class TestDemoConfigDiscovery:
    """Test the auto-discovery module (no HTTP needed)."""

    def test_discoveryFindsInvestorConfig(self):
        from modules.demoConfigs import _getAvailableDemoConfigs
        configs = _getAvailableDemoConfigs()
        assert "investor-demo-2026" in configs, f"Available configs: {list(configs.keys())}"

    def test_getByCodeReturnsInstance(self):
        from modules.demoConfigs import _getDemoConfigByCode
        cfg = _getDemoConfigByCode("investor-demo-2026")
        assert cfg is not None
        assert cfg.code == "investor-demo-2026"
        assert cfg.label == "Investor Demo April 2026"

    def test_getByCodeReturnsNoneForUnknown(self):
        from modules.demoConfigs import _getDemoConfigByCode
        cfg = _getDemoConfigByCode("nonexistent-config")
        assert cfg is None

    def test_toDictHasRequiredFields(self):
        from modules.demoConfigs import _getDemoConfigByCode
        cfg = _getDemoConfigByCode("investor-demo-2026")
        d = cfg.toDict()
        assert "code" in d
        assert "label" in d
        assert "description" in d
        assert d["code"] == "investor-demo-2026"


class TestDemoConfigApiEndpoints:
    """Test API endpoints via TestClient."""

    @pytest.fixture(scope="class")
    def client(self):
        try:
            from app import app
            from fastapi.testclient import TestClient
            return TestClient(app)
        except Exception as e:
            pytest.skip(f"Cannot create TestClient: {e}")

    def test_listEndpointRejectsUnauthenticated(self, client):
        response = client.get("/api/admin/demo-config")
        assert response.status_code in (401, 403)

    def test_loadEndpointRejectsUnauthenticated(self, client):
        response = client.post("/api/admin/demo-config/investor-demo-2026/load")
        assert response.status_code in (401, 403)

    def test_removeEndpointRejectsUnauthenticated(self, client):
        response = client.post("/api/admin/demo-config/investor-demo-2026/remove")
        assert response.status_code in (401, 403)
