from unittest.mock import AsyncMock

import pytest
from fastapi import HTTPException

from app.main import block_doctor, vendor_keys  # Import your actual function
from app.models import BlockDoctorRequest  # Import your request model


@pytest.fixture(autouse=True)
def setup_vendor_keys():
    # Ensure vendor_keys contains vendor_1 for tests.
    vendor_keys["vendor_1"] = "vendor_1_redis_list"
    yield
    # Optionally, cleanup vendor_keys after the test
    vendor_keys.pop("vendor_1", None)


@pytest.mark.asyncio
async def test_block_doctor_success(mocker):
    # Patch the redis instance
    mock_redis = mocker.patch("app.main.redis")
    mock_redis.hget = AsyncMock(return_value=None)
    mock_redis.hset = AsyncMock()

    request = BlockDoctorRequest(
        block_doctor_id="doctor_123", vendor_id="vendor_1", prescription_id="rx_001"
    )

    response = await block_doctor(request)
    mock_redis.hset.assert_called_with("DOCTOR_ASSIGNMENT_KEY", "doctor_123", "rx_001")
    assert response  # Adjust assertions based on your response structure


@pytest.mark.asyncio
async def test_block_doctor_already_assigned(mocker):
    mock_redis = mocker.patch("app.main.redis")
    mock_redis.hget = AsyncMock(return_value="rx_999")

    request = BlockDoctorRequest(
        block_doctor_id="doctor_123", vendor_id="vendor_1", prescription_id="rx_001"
    )

    with pytest.raises(HTTPException) as exc_info:
        await block_doctor(request)

    assert exc_info.value.status_code == 400
    assert "Doctor doctor_123 is already assigned to prescription rx_9999." in str(
        exc_info.value
    )
