# #region Test.Api.ProfileRoutes [C:3] [TYPE Module] [SEMANTICS test,profile,api,preferences,superset]
# @BRIEF Tests for profile.py — preferences CRUD and Superset account lookup.
# @RELATION BINDS_TO -> [ProfileApiModule]
# @TEST_EDGE: update_validation_error -> 422
# @TEST_EDGE: update_authorization_error -> 403
# @TEST_EDGE: superset_env_not_found -> 404

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 AsyncMock, 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.profile import router
    from src.dependencies import get_current_user, get_db, get_config_manager, get_plugin_loader
    from src.schemas.auth import User, RoleSchema

    app = FastAPI()
    app.include_router(router)

    mock_user = User(
        id="user-1", username="testuser", email="test@example.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,
        get_db: lambda: MagicMock(),
        get_config_manager: lambda: MagicMock(),
        get_plugin_loader: lambda: None,
    }
    if overrides:
        defaults.update(overrides)
    for dep, mock_fn in defaults.items():
        app.dependency_overrides[dep] = mock_fn
    return TestClient(app)


# ── get_preferences ──

class TestGetPreferences:
    """GET /api/profile/preferences"""

    def test_get_preferences_success(self):
        from datetime import datetime, UTC
        with patch("src.api.routes.profile.ProfileService") as MockService:
            instance = MockService.return_value
            instance.get_my_preference.return_value = {
                "status": "success",
                "preference": {
                    "user_id": "user-1",
                    "show_only_my_dashboards": True,
                    "show_only_slug_dashboards": True,
                    "superset_username": "admin",
                    "created_at": datetime.now(UTC).isoformat(),
                    "updated_at": datetime.now(UTC).isoformat(),
                },
                "security": {"read_only": False},
            }
            client = _make_client()
            resp = client.get("/api/profile/preferences")
        assert resp.status_code == 200
        data = resp.json()
        assert data["status"] == "success"
        assert data["preference"]["show_only_my_dashboards"] is True


# ── update_preferences ──

class TestUpdatePreferences:
    """PATCH /api/profile/preferences"""

    def test_update_success(self):
        from datetime import datetime, UTC
        with patch("src.api.routes.profile.ProfileService") as MockService:
            instance = MockService.return_value
            instance.update_my_preference.return_value = {
                "status": "success",
                "preference": {
                    "user_id": "user-1",
                    "show_only_my_dashboards": False,
                    "show_only_slug_dashboards": True,
                    "created_at": datetime.now(UTC).isoformat(),
                    "updated_at": datetime.now(UTC).isoformat(),
                },
                "security": {"read_only": False},
            }
            client = _make_client()
            resp = client.patch("/api/profile/preferences", json={
                "show_only_my_dashboards": False,
            })
        assert resp.status_code == 200
        data = resp.json()
        assert data["preference"]["show_only_my_dashboards"] is False

    def test_update_validation_error_422(self):
        from src.services.profile_service import ProfileValidationError
        with patch("src.api.routes.profile.ProfileService") as MockService:
            instance = MockService.return_value
            instance.update_my_preference.side_effect = ProfileValidationError(
                [{"field": "show_only_my_dashboards", "message": "Invalid value"}]
            )
            client = _make_client()
            resp = client.patch("/api/profile/preferences", json={
                "show_only_my_dashboards": "not-a-boolean",
            })
        assert resp.status_code == 422

    def test_update_authorization_error_403(self):
        from src.services.profile_service import ProfileAuthorizationError
        with patch("src.api.routes.profile.ProfileService") as MockService:
            instance = MockService.return_value
            instance.update_my_preference.side_effect = ProfileAuthorizationError(
                "Cross-user mutation blocked"
            )
            client = _make_client()
            resp = client.patch("/api/profile/preferences", json={
                "show_only_my_dashboards": True,
            })
        assert resp.status_code == 403
        assert "Cross-user mutation" in resp.text


# ── lookup_superset_accounts ──

class TestLookupSupersetAccounts:
    """GET /api/profile/superset-accounts"""

    def test_lookup_success(self):
        with patch("src.api.routes.profile.ProfileService") as MockService:
            instance = MockService.return_value
            instance.lookup_superset_accounts = AsyncMock(return_value={
                "status": "success",
                "environment_id": "env-1",
                "page_index": 0,
                "page_size": 20,
                "total": 1,
                "items": [{"environment_id": "env-1", "username": "admin"}],
            })
            client = _make_client()
            resp = client.get("/api/profile/superset-accounts?environment_id=env-1")
        assert resp.status_code == 200
        data = resp.json()
        assert len(data["items"]) == 1

    def test_lookup_with_search_and_pagination(self):
        with patch("src.api.routes.profile.ProfileService") as MockService:
            instance = MockService.return_value
            instance.lookup_superset_accounts = AsyncMock(return_value={
                "status": "success",
                "environment_id": "env-1",
                "page_index": 0,
                "page_size": 10,
                "total": 1,
                "items": [{"environment_id": "env-1", "username": "analyst"}],
            })
            client = _make_client()
            resp = client.get(
                "/api/profile/superset-accounts?environment_id=env-1"
                "&search=analyst&page_index=0&page_size=10"
                "&sort_column=username&sort_order=asc"
            )
        assert resp.status_code == 200
        data = resp.json()
        assert data["items"][0]["username"] == "analyst"

    def test_lookup_env_not_found_404(self):
        from src.services.profile_service import EnvironmentNotFoundError
        with patch("src.api.routes.profile.ProfileService") as MockService:
            instance = MockService.return_value
            instance.lookup_superset_accounts = AsyncMock(
                side_effect=EnvironmentNotFoundError("Environment not found: env-ghost")
            )
            client = _make_client()
            resp = client.get("/api/profile/superset-accounts?environment_id=env-ghost")
        assert resp.status_code == 404

    def test_lookup_missing_environment_id_422(self):
        # Required Query parameter environment_id missing -> FastAPI 422
        client = _make_client()
        resp = client.get("/api/profile/superset-accounts")
        assert resp.status_code == 422
# #endregion Test.Api.ProfileRoutes
