from django.test import TestCase
from graphene.test import Client
from orders_app.schema import schema

class OrdersGraphQLTestCase(TestCase):
    def setUp(self):
        self.client = Client(schema)
    
    def test_get_team_orders(self):
        """Тест getTeamOrders"""
        query = '''
        {
            getTeamOrders(teamUuid: "4993148a-cd2b-4987-b3f2-0f92b7479885") {
                uuid
                name
                totalAmount
                sourceLocationName
                destinationLocationName
                orderLines {
                    productName
                    quantity
                    unit
                }
                stages {
                    name
                    stageType
                    transportType
                }
            }
        }
        '''
        result = self.client.execute(query)
        print(f"\n=== TEAM ORDERS TEST ===")
        print(f"Result: {result}")
        
        if result.get('errors'):
            print(f"ERRORS: {result['errors']}")
        
        if result.get('data'):
            orders = result['data']['getTeamOrders']
            print(f"Found {len(orders)} orders")
            for order in orders:
                print(f"Order: {order.get('name')} - {order.get('totalAmount')}")
                if order.get('stages'):
                    print(f"  Stages: {len(order['stages'])}")
    
    def test_get_order_single(self):
        """Тест getOrder для конкретного заказа"""
        query = '''
        {
            getOrder(orderUuid: "order-coffee-kenya-2024") {
                uuid
                name
                totalAmount
                sourceLocationName
                destinationLocationName
                orderLines {
                    productName
                    quantity
                    unit
                }
                stages {
                    name
                    stageType
                    transportType
                    trips {
                        name
                        company {
                            name
                        }
                        plannedWeight
                        weightAtLoading
                    }
                }
            }
        }
        '''
        result = self.client.execute(query)
        print(f"\n=== SINGLE ORDER TEST ===")
        print(f"Result: {result}")
        
        if result.get('errors'):
            print(f"ERRORS: {result['errors']}")
        
        if result.get('data') and result['data']['getOrder']:
            order = result['data']['getOrder']
            print(f"Order: {order.get('name')}")
            print(f"Amount: {order.get('totalAmount')}")
            print(f"Route: {order.get('sourceLocationName')} → {order.get('destinationLocationName')}")
            
            if order.get('orderLines'):
                print(f"Order lines: {len(order['orderLines'])}")
                for line in order['orderLines']:
                    print(f"  - {line.get('productName')}: {line.get('quantity')} {line.get('unit')}")
            
            if order.get('stages'):
                print(f"Stages: {len(order['stages'])}")
                for stage in order['stages']:
                    print(f"  - {stage.get('name')} ({stage.get('stageType')})")
                    if stage.get('trips'):
                        print(f"    Trips: {len(stage['trips'])}")
    
    def test_schema_types(self):
        """Тест доступных типов в схеме"""
        query = '{ __schema { types { name } } }'
        result = self.client.execute(query)
        
        print(f"\n=== SCHEMA TYPES ===")
        if result.get('data'):
            types = [t['name'] for t in result['data']['__schema']['types']]
            print(f"Available types: {types}")
            
            # Проверяем что есть нужные типы
            required_types = ['OrderType', 'StageType', 'TripType', 'CompanyType']
            for req_type in required_types:
                if req_type in types:
                    print(f"✅ {req_type} - OK")
                else:
                    print(f"❌ {req_type} - MISSING")