# #region Test.Api.GitEnvironmentRoutes [C:2] [TYPE Module] [SEMANTICS test,git,environment,routes]
# @BRIEF Unit tests for Git environment routes.
# @RELATION BINDS_TO -> [GitEnvironmentRoutes]
# @TEST_EDGE: empty_list -> 200

import os

os.environ.setdefault("DATABASE_URL", "sqlite:///:memory:")
os.environ.setdefault("AUTH_DATABASE_URL", "sqlite:///:memory:")
os.environ.setdefault("SECRET_KEY", "test-secret-key-for-tests")

import sys
from pathlib import Path
from unittest.mock import MagicMock, patch

import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient

_src = str(Path(__file__).resolve().parent.parent.parent / "src")
if _src not in sys.path:
    sys.path.insert(0, _src)


def _make_client(overrides: dict | None = None) -> TestClient:
    from src.api.routes.git._environment_routes import router
    from src.dependencies import get_current_user, has_permission
    from src.schemas.auth import User, RoleSchema

    app = FastAPI()
    app.include_router(router, prefix="/api/git")

    mock_user = User(
        id="admin-1", username="admin", email="admin@x.com",
        auth_source="LOCAL",
        created_at=__import__("datetime").datetime.now(),
        roles=[RoleSchema(id="r1", name="Admin", description="", permissions=[])],
    )

    defaults = {
        get_current_user: lambda: mock_user,
    }
    if overrides:
        defaults.update(overrides)
    for dep, mock_fn in defaults.items():
        app.dependency_overrides[dep] = mock_fn
    return TestClient(app)


class TestGetEnvironments:
    """GET /api/git/environments"""

    def test_list_environments_success(self):
        """Happy path: returns deployment environments."""
        mock_config = MagicMock()
        env1 = MagicMock()
        env1.id = "env-1"
        env1.name = "Production"
        env1.url = "https://superset.prod.com"
        env2 = MagicMock()
        env2.id = "env-2"
        env2.name = "Staging"
        env2.url = "https://superset.staging.com"
        mock_config.get_environments.return_value = [env1, env2]

        from src.dependencies import get_config_manager
        client = _make_client({get_config_manager: lambda: mock_config})
        resp = client.get("/api/git/environments")
        assert resp.status_code == 200
        data = resp.json()
        assert len(data) == 2
        assert data[0]["id"] == "env-1"
        assert data[0]["name"] == "Production"
        assert data[0]["superset_url"] == "https://superset.prod.com"
        assert data[0]["is_active"] is True

    def test_list_environments_empty(self):
        """Empty list returns 200."""
        mock_config = MagicMock()
        mock_config.get_environments.return_value = []

        from src.dependencies import get_config_manager
        client = _make_client({get_config_manager: lambda: mock_config})
        resp = client.get("/api/git/environments")
        assert resp.status_code == 200
        assert resp.json() == []
# #endregion Test.Api.GitEnvironmentRoutes
