import pytest
from fastapi.testclient import TestClient
from unittest.mock import AsyncMock, MagicMock, patch
from datetime import date
import uuid

from app.main import app
from app.api.batch import SalesSummaryBatchRequest, SalesSummary

client = TestClient(app)

@pytest.fixture
def mock_sales_service():
    with patch("app.api.batch.get_sales_service") as mock:
        service = AsyncMock()
        mock.return_value = service
        yield service

@pytest.fixture
def mock_current_user():
    with patch("app.api.batch.get_current_user_dep") as mock:
        mock.return_value = {
            "user_id": str(uuid.uuid4()),
            "role": "admin",
            "tenant_id": str(uuid.uuid4())
        }
        yield mock

def test_get_sales_summary_batch_success(mock_sales_service, mock_current_user):
    # Setup
    tenant_id_1 = str(uuid.uuid4())
    tenant_id_2 = str(uuid.uuid4())
    
    request_data = {
        "tenant_ids": [tenant_id_1, tenant_id_2],
        "start_date": "2025-01-01",
        "end_date": "2025-01-31"
    }
    
    # Mock service response
    mock_sales_service.get_sales_analytics.side_effect = [
        {
            "total_revenue": 1000.0,
            "total_orders": 10,
            "average_order_value": 100.0
        },
        {
            "total_revenue": 2000.0,
            "total_orders": 20,
            "average_order_value": 100.0
        }
    ]
    
    # Execute
    response = client.post("/api/v1/batch/sales-summary", json=request_data)
    
    # Verify
    assert response.status_code == 200
    data = response.json()
    assert len(data) == 2
    assert data[tenant_id_1]["total_revenue"] == 1000.0
    assert data[tenant_id_2]["total_revenue"] == 2000.0
    
    # Verify service calls
    assert mock_sales_service.get_sales_analytics.call_count == 2

def test_get_sales_summary_batch_empty(mock_sales_service, mock_current_user):
    # Setup
    request_data = {
        "tenant_ids": [],
        "start_date": "2025-01-01",
        "end_date": "2025-01-31"
    }
    
    # Execute
    response = client.post("/api/v1/batch/sales-summary", json=request_data)
    
    # Verify
    assert response.status_code == 200
    assert response.json() == {}

def test_get_sales_summary_batch_limit_exceeded(mock_sales_service, mock_current_user):
    # Setup
    tenant_ids = [str(uuid.uuid4()) for _ in range(101)]
    request_data = {
        "tenant_ids": tenant_ids,
        "start_date": "2025-01-01",
        "end_date": "2025-01-31"
    }
    
    # Execute
    response = client.post("/api/v1/batch/sales-summary", json=request_data)
    
    # Verify
    assert response.status_code == 400
    assert "Maximum 100 tenant IDs allowed" in response.json()["detail"]
