import graphene
import requests
from django.conf import settings
from ..permissions import require_scopes


class OrderType(graphene.ObjectType):
    uuid = graphene.String()
    name = graphene.String()
    teamUuid = graphene.String()
    userId = graphene.String()
    status = graphene.String()
    totalAmount = graphene.Float()
    currency = graphene.String()
    sourceLocationUuid = graphene.String()
    sourceLocationName = graphene.String()
    destinationLocationUuid = graphene.String()
    destinationLocationName = graphene.String()
    createdAt = graphene.String()
    updatedAt = graphene.String()
    notes = graphene.String()
    orderLines = graphene.List(lambda: OrderLineType)
    stages = graphene.List(lambda: StageType)


class OrderLineType(graphene.ObjectType):
    uuid = graphene.String()
    productUuid = graphene.String()
    productName = graphene.String()
    quantity = graphene.Float()
    unit = graphene.String()
    priceUnit = graphene.Float()
    subtotal = graphene.Float()
    currency = graphene.String()
    notes = graphene.String()


class CompanyType(graphene.ObjectType):
    uuid = graphene.String()
    name = graphene.String()
    taxId = graphene.String()
    country = graphene.String()
    countryCode = graphene.String()
    active = graphene.Boolean()


class TripType(graphene.ObjectType):
    uuid = graphene.String()
    name = graphene.String()
    sequence = graphene.Int()
    company = graphene.Field(CompanyType)
    plannedLoadingDate = graphene.String()
    actualLoadingDate = graphene.String()
    realLoadingDate = graphene.String()
    plannedUnloadingDate = graphene.String()
    actualUnloadingDate = graphene.String()
    plannedWeight = graphene.Float()
    weightAtLoading = graphene.Float()
    weightAtUnloading = graphene.Float()


class StageType(graphene.ObjectType):
    uuid = graphene.String()
    name = graphene.String()
    sequence = graphene.Int()
    stageType = graphene.String()
    transportType = graphene.String()
    sourceLocationName = graphene.String()
    sourceLatitude = graphene.Float()
    sourceLongitude = graphene.Float()
    destinationLocationName = graphene.String()
    destinationLatitude = graphene.Float()
    destinationLongitude = graphene.Float()
    locationName = graphene.String()
    locationLatitude = graphene.Float()
    locationLongitude = graphene.Float()
    selectedCompany = graphene.Field(CompanyType)
    trips = graphene.List(TripType)


class TeamQuery(graphene.ObjectType):
    """Team schema - Team Access Token authentication"""
    getTeamOrders = graphene.List(OrderType)
    getOrder = graphene.Field(OrderType, orderUuid=graphene.String(required=True))

    @require_scopes("teams:member")
    def resolve_getTeamOrders(self, info):
        user_id = getattr(info.context, 'user_id', None)
        team_uuid = getattr(info.context, 'team_uuid', None)

        if not user_id:
            raise Exception("User not authenticated")

        if not team_uuid:
            return []

        try:
            url = f"http://{settings.ODOO_INTERNAL_URL}/fastapi/orders/orders/team/{team_uuid}"
            response = requests.get(url, timeout=10)

            if response.status_code == 200:
                data = response.json()
                result = []
                for order_data in data:
                    order = OrderType(
                        uuid=order_data.get('uuid'),
                        name=order_data.get('name'),
                        teamUuid=order_data.get('team_uuid'),
                        userId=order_data.get('user_id'),
                        status='active',
                        totalAmount=order_data.get('total_amount'),
                        currency=order_data.get('currency'),
                        sourceLocationUuid=order_data.get('source_location_uuid'),
                        sourceLocationName=order_data.get('source_location_name'),
                        destinationLocationUuid=order_data.get('destination_location_uuid'),
                        destinationLocationName=order_data.get('destination_location_name'),
                        createdAt=order_data.get('created_at'),
                        updatedAt=order_data.get('updated_at'),
                        notes=order_data.get('notes', ''),
                        orderLines=[
                            OrderLineType(
                                uuid=line.get('uuid'),
                                productUuid=line.get('product_uuid'),
                                productName=line.get('product_name'),
                                quantity=line.get('quantity'),
                                unit=line.get('unit'),
                                priceUnit=line.get('price_unit'),
                                subtotal=line.get('subtotal'),
                                currency=line.get('currency'),
                                notes=line.get('notes', '')
                            ) for line in order_data.get('order_lines', [])
                        ],
                        stages=[
                            StageType(
                                uuid=stage.get('uuid'),
                                name=stage.get('name'),
                                sequence=stage.get('sequence'),
                                stageType=stage.get('stage_type'),
                                transportType=stage.get('transport_type'),
                                sourceLocationName=stage.get('source_location_name'),
                                destinationLocationName=stage.get('destination_location_name'),
                                locationName=stage.get('location_name'),
                                selectedCompany=CompanyType(
                                    uuid=stage.get('selected_company', {}).get('uuid', ''),
                                    name=stage.get('selected_company', {}).get('name', ''),
                                    taxId=stage.get('selected_company', {}).get('tax_id', ''),
                                    country=stage.get('selected_company', {}).get('country', ''),
                                    countryCode=stage.get('selected_company', {}).get('country_code', ''),
                                    active=stage.get('selected_company', {}).get('active', True)
                                ) if stage.get('selected_company') else None,
                                trips=[
                                    TripType(
                                        uuid=trip.get('uuid'),
                                        name=trip.get('name'),
                                        sequence=trip.get('sequence'),
                                        company=CompanyType(
                                            uuid=trip.get('company', {}).get('uuid', ''),
                                            name=trip.get('company', {}).get('name', ''),
                                            taxId=trip.get('company', {}).get('tax_id', ''),
                                            country=trip.get('company', {}).get('country', ''),
                                            countryCode=trip.get('company', {}).get('country_code', ''),
                                            active=trip.get('company', {}).get('active', True)
                                        ) if trip.get('company') else None,
                                        plannedLoadingDate=trip.get('planned_loading_date'),
                                        actualLoadingDate=trip.get('actual_loading_date'),
                                        realLoadingDate=trip.get('real_loading_date'),
                                        plannedUnloadingDate=trip.get('planned_unloading_date'),
                                        actualUnloadingDate=trip.get('actual_unloading_date'),
                                        plannedWeight=trip.get('planned_weight'),
                                        weightAtLoading=trip.get('weight_at_loading'),
                                        weightAtUnloading=trip.get('weight_at_unloading')
                                    ) for trip in stage.get('trips', [])
                                ]
                            ) for stage in order_data.get('stages', [])
                        ]
                    )
                    result.append(order)
                return result
            else:
                return []

        except Exception as e:
            print(f"Error calling Odoo: {e}")
            return []

    @require_scopes("teams:member")
    def resolve_getOrder(self, info, orderUuid):
        user_id = getattr(info.context, 'user_id', None)
        team_uuid = getattr(info.context, 'team_uuid', None)

        if not user_id or not team_uuid:
            raise Exception("User not authenticated")

        try:
            url = f"http://{settings.ODOO_INTERNAL_URL}/fastapi/orders/orders/{orderUuid}"
            response = requests.get(url, timeout=10)

            if response.status_code == 200:
                order_data = response.json()

                if order_data.get('team_uuid') != team_uuid:
                    raise Exception("Access denied: order belongs to different team")

                order = OrderType(
                    uuid=order_data.get('uuid'),
                    name=order_data.get('name'),
                    teamUuid=order_data.get('team_uuid'),
                    userId=order_data.get('user_id'),
                    status='active',
                    totalAmount=order_data.get('total_amount'),
                    currency=order_data.get('currency'),
                    sourceLocationUuid=order_data.get('source_location_uuid'),
                    sourceLocationName=order_data.get('source_location_name'),
                    destinationLocationUuid=order_data.get('destination_location_uuid'),
                    destinationLocationName=order_data.get('destination_location_name'),
                    createdAt=order_data.get('created_at'),
                    updatedAt=order_data.get('updated_at'),
                    notes=order_data.get('notes', ''),
                    orderLines=[
                        OrderLineType(
                            uuid=line.get('uuid'),
                            productUuid=line.get('product_uuid'),
                            productName=line.get('product_name'),
                            quantity=line.get('quantity'),
                            unit=line.get('unit'),
                            priceUnit=line.get('price_unit'),
                            subtotal=line.get('subtotal'),
                            currency=line.get('currency'),
                            notes=line.get('notes', '')
                        ) for line in order_data.get('order_lines', [])
                    ],
                    stages=[
                        StageType(
                            uuid=stage.get('uuid'),
                            name=stage.get('name'),
                            sequence=stage.get('sequence'),
                            stageType=stage.get('stage_type'),
                            transportType=stage.get('transport_type'),
                            sourceLocationName=stage.get('source_location_name'),
                            sourceLatitude=stage.get('source_latitude'),
                            sourceLongitude=stage.get('source_longitude'),
                            destinationLocationName=stage.get('destination_location_name'),
                            destinationLatitude=stage.get('destination_latitude'),
                            destinationLongitude=stage.get('destination_longitude'),
                            locationName=stage.get('location_name'),
                            locationLatitude=stage.get('location_latitude'),
                            locationLongitude=stage.get('location_longitude'),
                            selectedCompany=CompanyType(
                                uuid=stage.get('selected_company', {}).get('uuid', ''),
                                name=stage.get('selected_company', {}).get('name', ''),
                                taxId=stage.get('selected_company', {}).get('tax_id', ''),
                                country=stage.get('selected_company', {}).get('country', ''),
                                countryCode=stage.get('selected_company', {}).get('country_code', ''),
                                active=stage.get('selected_company', {}).get('active', True)
                            ) if stage.get('selected_company') else None,
                            trips=[
                                TripType(
                                    uuid=trip.get('uuid'),
                                    name=trip.get('name'),
                                    sequence=trip.get('sequence'),
                                    company=CompanyType(
                                        uuid=trip.get('company', {}).get('uuid', ''),
                                        name=trip.get('company', {}).get('name', ''),
                                        taxId=trip.get('company', {}).get('tax_id', ''),
                                        country=trip.get('company', {}).get('country', ''),
                                        countryCode=trip.get('company', {}).get('country_code', ''),
                                        active=trip.get('company', {}).get('active', True)
                                    ) if trip.get('company') else None,
                                    plannedLoadingDate=trip.get('planned_loading_date'),
                                    actualLoadingDate=trip.get('actual_loading_date'),
                                    realLoadingDate=trip.get('real_loading_date'),
                                    plannedUnloadingDate=trip.get('planned_unloading_date'),
                                    actualUnloadingDate=trip.get('actual_unloading_date'),
                                    plannedWeight=trip.get('planned_weight'),
                                    weightAtLoading=trip.get('weight_at_loading'),
                                    weightAtUnloading=trip.get('weight_at_unloading')
                                ) for trip in stage.get('trips', [])
                            ]
                        ) for stage in order_data.get('stages', [])
                    ]
                )
                return order
            else:
                return None

        except Exception as e:
            print(f"Exception: {e}")
            return None


team_schema = graphene.Schema(query=TeamQuery)
