import pytest
from unittest.mock import MagicMock

def test_create_order_authorized(client, db_mock, mocker):
    # Mock background tasks to avoid side effects
    mocker.patch("fastapi.BackgroundTasks.add_task")
    
    db_mock.execute_query.side_effect = None
    db_mock.execute_query.return_value = [{"id": 1, "name_en": "PLA", "price_per_cm3": 0.05}]
    db_mock.execute_commit.return_value = 123
    
    import auth_utils
    token = auth_utils.create_access_token({"sub": "test@example.com", "id": 1, "role": "user"})
    
    response = client.post(
        "/orders",
        headers={"Authorization": f"Bearer {token}"},
        data={
            "first_name": "Test",
            "last_name": "User",
            "phone": "12345678",
            "email": "test@example.com",
            "shipping_address": "123 Test St",
            "material_id": 1,
            "quantity": 2
        }
    )
    
    assert response.status_code == 200
    assert response.json()["order_id"] == 123

def test_create_order_no_material_defaults(client, db_mock, mocker):
    mocker.patch("fastapi.BackgroundTasks.add_task")
    db_mock.execute_query.side_effect = None
    db_mock.execute_query.return_value = [] # Material not found
    
    response = client.post(
        "/orders",
        data={
            "first_name": "Test",
            "last_name": "User",
            "phone": "12345678",
            "email": "test@example.com",
            "shipping_address": "123 Test St",
            "material_id": 999,
            "quantity": 1
        }
    )
    
    # The current implementation defaults to "Unknown" material instead of 404
    assert response.status_code == 200
    assert response.json()["status"] == "success"
