import pytest
import auth_utils

def test_submit_review_unauthorized(client):
    response = client.post("/orders/123/review", json={"rating": 5, "review_text": "Great!"})
    assert response.status_code == 401
    assert response.json()["detail"] == "Not authenticated"

def test_submit_review_success(client, db_mock, mocker):
    # Mock order ownership check
    db_mock.execute_query.return_value = [{"id": 123, "status": "shipped"}]
    db_mock.execute_commit.return_value = None
    
    # Mock audit log
    mocker.patch("routers.orders.audit_service.log", new_callable=mocker.AsyncMock)
    
    token = auth_utils.create_access_token({"id": 1, "role": "user", "email": "user@example.com"})
    
    response = client.post(
        "/orders/123/review",
        headers={"Authorization": f"Bearer {token}"},
        json={"rating": 5, "review_text": "Excellent service!"}
    )
    
    assert response.status_code == 200
    assert "Review submitted successfully" in response.json()["message"]
    # Verify DB update
    assert db_mock.execute_commit.called

def test_admin_get_reviews_unauthorized(client):
    response = client.get("/admin/reviews")
    assert response.status_code == 401

def test_admin_get_reviews_as_user(client):
    token = auth_utils.create_access_token({"id": 1, "role": "user", "email": "user@example.com"})
    response = client.get("/admin/reviews", headers={"Authorization": f"Bearer {token}"})
    assert response.status_code == 403 # Admin role required

def test_admin_toggle_review_approval(client, db_mock):
    # Mock admin user
    token = auth_utils.create_access_token({"id": 99, "role": "admin", "email": "admin@radionica3d.me"})
    
    # Mock existing order info for the PATCH update
    db_mock.execute_query.return_value = [{"id": 123, "user_id": 1, "status": "completed"}]
    
    response = client.patch(
        "/orders/123",
        headers={"Authorization": f"Bearer {token}"},
        json={"review_approved": True}
    )
    
    assert response.status_code == 200
    assert response.json()["status"] == "updated"
    # Verify that review_approved was in the update query
    found_approved = False
    for call in db_mock.execute_commit.call_args_list:
        if "review_approved" in call[0][0]:
            found_approved = True
            break
    assert found_approved
