from unittest.mock import AsyncMock, patch

import pytest
from fastapi.testclient import TestClient

from fastapi.testclient import TestClient

from app.main import app

client = TestClient(app)

# Example: Test /add_vendor endpoint
@patch("app.main.redis")
@pytest.mark.asyncio
async def test_add_vendor_success(mock_redis):
    mock_redis.rpush = AsyncMock()
    payload = {
        "vendor": "unit_vendor",
        "doctors": ["doc1"],
        "concurrent_doctors": 1,
        "immediate_unblock": False,
        "rx_max_hold_time": 60,
        "rx_max_block_time": 30,
        "rx_notification_interval": 10
    }
    response = client.post("/api/1rx/v1/scheduler/add_vendor", json=payload)
    assert response.status_code == 200
    assert "added to the pool" in response.json()["data"]["message"] or "already exists" in response.json()["data"]["message"]

# Example: Test /add_doctor endpoint
@patch("app.main.redis")
@pytest.mark.asyncio
async def test_add_doctor_success(mock_redis):
    mock_redis.lrange = AsyncMock(return_value=[])
    mock_redis.hgetall = AsyncMock(return_value={})
    mock_redis.rpush = AsyncMock()
    mock_redis.lrem = AsyncMock()
    payload = {"vendor_id": "unit_vendor", "id": "doc2"}
    response = client.post("/api/1rx/v1/scheduler/add_doctor", json=payload)
    assert response.status_code == 200
    assert "added to vendor" in response.json()["data"]["message"]

# Example: Test /remove_doctor endpoint
@patch("app.main.redis")
@pytest.mark.asyncio
async def test_remove_doctor_not_found(mock_redis):
    mock_redis.lrange = AsyncMock(return_value=[])
    payload = {"vendor_id": "unit_vendor", "id": "doc3"}
    response = client.post("/api/1rx/v1/scheduler/remove_doctor", json=payload)
    assert response.status_code == 200
    assert "not found" in response.json()["data"]["message"]

# Example: Test /assign_doctor endpoint (failure: vendor not found)
@patch("app.main.redis")
@pytest.mark.asyncio
async def test_assign_doctor_vendor_not_found(mock_redis):
    payload = {"vendor_id": "not_exist_vendor", "prescription_id": "rx1"}
    response = client.post("/api/1rx/v1/scheduler/assign_doctor", json=payload)
    assert response.status_code == 404

# Example: Test /list_all_cached_doctors endpoint
@patch("app.main.redis")
@pytest.mark.asyncio
async def test_list_all_cached_doctors_empty(mock_redis):
    mock_redis.lrange = AsyncMock(return_value=[])
    response = client.get("/api/1rx/v1/scheduler/list_all_cached_doctors?vendor_id=unit_vendor")
    assert response.status_code == 200
    assert response.json()["data"]["doctor_ids"] == []
