"""
Backend API Tests for Nadiplayer IPTV App
Tests: Health check, Auth (admin login), Public endpoints
"""
import pytest
import requests
import os

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

class TestHealthCheck:
    """Basic API health check tests"""
    
    def test_api_root_accessible(self):
        """Test that /api/ endpoint returns Hello World"""
        response = requests.get(f"{BASE_URL}/api/")
        assert response.status_code == 200
        data = response.json()
        assert "message" in data
        assert data["message"] == "Hello World"
        print(f"✓ API root accessible: {data}")


class TestAuthEndpoints:
    """Authentication endpoint tests"""
    
    def test_admin_login_success(self):
        """Test admin login with correct credentials"""
        response = requests.post(f"{BASE_URL}/api/auth/login", json={
            "username": "admin",
            "password": "admin123"
        })
        assert response.status_code == 200, f"Login failed: {response.text}"
        data = response.json()
        
        # Validate response structure
        assert "access_token" in data, "Missing access_token in response"
        assert "token_type" in data, "Missing token_type in response"
        assert "user" in data, "Missing user in response"
        
        # Validate user data
        user = data["user"]
        assert user["username"] == "admin"
        assert user["role"] == "admin"
        assert "id" in user
        print(f"✓ Admin login successful: {user['username']} (role: {user['role']})")
        
        return data["access_token"]
    
    def test_admin_login_invalid_password(self):
        """Test admin login with wrong password"""
        response = requests.post(f"{BASE_URL}/api/auth/login", json={
            "username": "admin",
            "password": "wrongpassword"
        })
        assert response.status_code == 401
        data = response.json()
        assert "detail" in data
        print(f"✓ Invalid password correctly rejected: {data['detail']}")
    
    def test_admin_login_invalid_username(self):
        """Test login with non-existent user"""
        response = requests.post(f"{BASE_URL}/api/auth/login", json={
            "username": "nonexistent",
            "password": "admin123"
        })
        assert response.status_code == 401
        data = response.json()
        assert "detail" in data
        print(f"✓ Invalid username correctly rejected: {data['detail']}")
    
    def test_me_endpoint_without_auth(self):
        """Test /me endpoint without authentication"""
        response = requests.get(f"{BASE_URL}/api/auth/me")
        assert response.status_code == 401
        print("✓ /me endpoint correctly requires authentication")
    
    def test_me_endpoint_with_auth(self):
        """Test /me endpoint with valid token"""
        # First login to get token
        login_response = requests.post(f"{BASE_URL}/api/auth/login", json={
            "username": "admin",
            "password": "admin123"
        })
        assert login_response.status_code == 200
        token = login_response.json()["access_token"]
        
        # Now test /me endpoint
        response = requests.get(
            f"{BASE_URL}/api/auth/me",
            headers={"Authorization": f"Bearer {token}"}
        )
        assert response.status_code == 200
        data = response.json()
        assert data["username"] == "admin"
        assert data["role"] == "admin"
        print(f"✓ /me endpoint returns user data: {data['username']}")


class TestPublicEndpoints:
    """Public endpoint tests (no auth required)"""
    
    def test_playback_mode(self):
        """Test public playback mode endpoint"""
        response = requests.get(f"{BASE_URL}/api/public/playback-mode")
        assert response.status_code == 200
        data = response.json()
        print(f"✓ Playback mode endpoint accessible: {data}")
    
    def test_app_info(self):
        """Test public app info endpoint"""
        response = requests.get(f"{BASE_URL}/api/public/app-info")
        assert response.status_code == 200
        data = response.json()
        print(f"✓ App info endpoint accessible: {data}")
    
    def test_geo_endpoint(self):
        """Test public geo endpoint"""
        response = requests.get(f"{BASE_URL}/api/public/geo")
        assert response.status_code == 200
        data = response.json()
        print(f"✓ Geo endpoint accessible: {data}")


class TestTrialEndpoints:
    """Trial status endpoint tests"""
    
    def test_trial_status(self):
        """Test trial status endpoint"""
        response = requests.post(f"{BASE_URL}/api/trial/status", json={
            "hardware_id": "test_device_123"
        })
        assert response.status_code == 200
        data = response.json()
        print(f"✓ Trial status endpoint accessible: {data}")


class TestStatusEndpoints:
    """Status check CRUD tests"""
    
    def test_create_status_check(self):
        """Test creating a status check"""
        response = requests.post(f"{BASE_URL}/api/status", json={
            "client_name": "TEST_pytest_client"
        })
        assert response.status_code == 200
        data = response.json()
        assert "id" in data
        assert data["client_name"] == "TEST_pytest_client"
        print(f"✓ Status check created: {data['id']}")
    
    def test_get_status_checks(self):
        """Test getting all status checks"""
        response = requests.get(f"{BASE_URL}/api/status")
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        print(f"✓ Status checks retrieved: {len(data)} items")


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