"""
Test suite for Admin Alerts feature (iteration 11)
Tests the new /api/admin/alerts endpoint and regression tests for own-mode isolation
"""
import os
import pytest
import requests

BASE_URL = os.environ.get('REACT_APP_BACKEND_URL', 'https://nadiplayer-edit.preview.emergentagent.com').rstrip('/')

# Test credentials from /app/memory/test_credentials.md
ADMIN_CREDS = {"username": "admin", "password": "admin123"}
OWN_MODE_USER_CREDS = {"username": "googletest", "password": "test123"}


@pytest.fixture(scope="module")
def admin_token():
    """Get admin authentication token"""
    response = requests.post(
        f"{BASE_URL}/api/auth/login",
        json=ADMIN_CREDS,
        headers={"Content-Type": "application/json"}
    )
    assert response.status_code == 200, f"Admin login failed: {response.text}"
    data = response.json()
    assert "access_token" in data, "No access_token in admin login response"
    return data["access_token"]


@pytest.fixture(scope="module")
def googletest_token():
    """Get googletest user authentication token"""
    response = requests.post(
        f"{BASE_URL}/api/auth/login",
        json=OWN_MODE_USER_CREDS,
        headers={"Content-Type": "application/json"}
    )
    assert response.status_code == 200, f"googletest login failed: {response.text}"
    data = response.json()
    assert "access_token" in data, "No access_token in googletest login response"
    return data["access_token"]


class TestAdminAlerts:
    """Tests for the new /api/admin/alerts endpoint"""

    def test_admin_alerts_returns_unconfigured_own_users(self, admin_token):
        """Test that /api/admin/alerts returns unconfigured own-mode users"""
        response = requests.get(
            f"{BASE_URL}/api/admin/alerts",
            headers={"Authorization": f"Bearer {admin_token}"}
        )
        assert response.status_code == 200, f"Admin alerts failed: {response.text}"
        data = response.json()
        
        # Verify response structure
        assert "unconfigured_own_users" in data, "Missing unconfigured_own_users in response"
        unconfigured = data["unconfigured_own_users"]
        assert isinstance(unconfigured, list), "unconfigured_own_users should be a list"
        
        # Verify googletest is in the list
        usernames = [u["username"] for u in unconfigured]
        assert "googletest" in usernames, f"googletest not found in unconfigured users: {usernames}"
        
        # Verify googletest user data structure
        googletest_user = next(u for u in unconfigured if u["username"] == "googletest")
        assert "id" in googletest_user, "Missing id in user data"
        assert "username" in googletest_user, "Missing username in user data"
        assert "created_at" in googletest_user, "Missing created_at in user data"
        assert "days_remaining" in googletest_user, "Missing days_remaining in user data"
        assert googletest_user["days_remaining"] is not None, "days_remaining should not be None"
        print(f"✓ googletest found with {googletest_user['days_remaining']} days remaining")

    def test_admin_alerts_requires_admin_auth(self):
        """Test that /api/admin/alerts requires admin authentication"""
        # No auth
        response = requests.get(f"{BASE_URL}/api/admin/alerts")
        assert response.status_code == 401, f"Expected 401 without auth, got {response.status_code}"

    def test_admin_alerts_rejects_non_admin(self, googletest_token):
        """Test that /api/admin/alerts rejects non-admin users"""
        response = requests.get(
            f"{BASE_URL}/api/admin/alerts",
            headers={"Authorization": f"Bearer {googletest_token}"}
        )
        assert response.status_code == 403, f"Expected 403 for non-admin, got {response.status_code}"


class TestOwnModeIsolation:
    """Regression tests for own-mode isolation (BUG-7 fix)"""

    def test_shared_profiles_empty_for_own_mode_user(self, googletest_token):
        """Test that /api/shared-profiles returns empty for own-mode user"""
        response = requests.get(
            f"{BASE_URL}/api/shared-profiles",
            headers={"Authorization": f"Bearer {googletest_token}"}
        )
        assert response.status_code == 200, f"Shared profiles failed: {response.text}"
        data = response.json()
        
        # Verify empty profiles
        assert "profiles" in data, "Missing profiles in response"
        assert data["profiles"] == [], f"Expected empty profiles, got: {data['profiles']}"
        
        # Verify xtream_mode is 'own'
        assert data.get("xtream_mode") == "own", f"Expected xtream_mode='own', got: {data.get('xtream_mode')}"
        print("✓ /api/shared-profiles returns empty for own-mode user")

    def test_subscription_status_own_mode_not_configured(self, googletest_token):
        """Test that /api/subscription/status returns correct data for unconfigured own-mode user"""
        response = requests.get(
            f"{BASE_URL}/api/subscription/status",
            headers={"Authorization": f"Bearer {googletest_token}"}
        )
        assert response.status_code == 200, f"Subscription status failed: {response.text}"
        data = response.json()
        
        # Verify xtream_mode is 'own'
        assert data.get("xtream_mode") == "own", f"Expected xtream_mode='own', got: {data.get('xtream_mode')}"
        
        # Verify xtream_configured is false
        assert data.get("xtream_configured") == False, f"Expected xtream_configured=false, got: {data.get('xtream_configured')}"
        
        # Verify xtream credentials are empty
        xtream = data.get("xtream", {})
        assert xtream.get("server") == "", f"Expected empty server, got: {xtream.get('server')}"
        assert xtream.get("username") == "", f"Expected empty username, got: {xtream.get('username')}"
        assert xtream.get("password") == "", f"Expected empty password, got: {xtream.get('password')}"
        print("✓ /api/subscription/status returns xtream_mode='own', xtream_configured=false")


class TestAdminLogin:
    """Tests for admin login and redirect"""

    def test_admin_login_success(self):
        """Test that admin can login successfully"""
        response = requests.post(
            f"{BASE_URL}/api/auth/login",
            json=ADMIN_CREDS,
            headers={"Content-Type": "application/json"}
        )
        assert response.status_code == 200, f"Admin login failed: {response.text}"
        data = response.json()
        
        assert "access_token" in data, "Missing access_token"
        assert "user" in data, "Missing user"
        assert data["user"]["role"] == "admin", f"Expected role='admin', got: {data['user']['role']}"
        print("✓ Admin login successful")

    def test_googletest_login_success(self):
        """Test that googletest user can login successfully"""
        response = requests.post(
            f"{BASE_URL}/api/auth/login",
            json=OWN_MODE_USER_CREDS,
            headers={"Content-Type": "application/json"}
        )
        assert response.status_code == 200, f"googletest login failed: {response.text}"
        data = response.json()
        
        assert "access_token" in data, "Missing access_token"
        assert "user" in data, "Missing user"
        assert data["user"]["username"] == "googletest", f"Expected username='googletest', got: {data['user']['username']}"
        assert data["user"]["xtream_mode"] == "own", f"Expected xtream_mode='own', got: {data['user']['xtream_mode']}"
        print("✓ googletest login successful with xtream_mode='own'")


if __name__ == "__main__":
    pytest.main([__file__, "-v", "--tb=short"])
