"""Activities for Exchange service via GraphQL M2M endpoint."""
import logging
import httpx
from temporalio import activity

from optovia_workflows.types import (
    CreateOfferInExchangeInput,
    CreateOfferInExchangeResult,
    UpdateOfferWorkflowStatusInput,
    UpdateOfferWorkflowStatusResult,
)

from ..config import settings

logger = logging.getLogger(__name__)

CREATE_OFFER_MUTATION = """
mutation CreateOfferFromWorkflow($input: CreateOfferFromWorkflowInput!) {
  createOfferFromWorkflow(input: $input) {
    success
    message
    offer {
      uuid
    }
  }
}
"""

UPDATE_OFFER_STATUS_MUTATION = """
mutation UpdateOfferWorkflowStatus($input: UpdateOfferWorkflowStatusInput!) {
  updateOfferWorkflowStatus(input: $input) {
    success
    message
    offer {
      uuid
    }
  }
}
"""


@activity.defn(name="create_offer_in_exchange")
def create_offer_in_exchange(data: CreateOfferInExchangeInput) -> CreateOfferInExchangeResult:
    url = f"http://{settings.EXCHANGE_INTERNAL_URL}/graphql/m2m/"

    payload = {
        "offerUuid": data.offer_uuid,
        "teamUuid": data.team_uuid,
        "productUuid": data.product_uuid,
        "productName": data.product_name,
        "categoryName": data.category_name,
        "locationUuid": data.location_uuid,
        "locationName": data.location_name,
        "locationCountry": data.location_country,
        "locationCountryCode": data.location_country_code,
        "locationLatitude": data.location_latitude,
        "locationLongitude": data.location_longitude,
        "quantity": data.quantity,
        "unit": data.unit,
        "pricePerUnit": data.price_per_unit,
        "currency": data.currency,
        "description": data.description,
        "validUntil": data.valid_until,
        "terminusSchemaId": data.terminus_schema_id,
        "terminusDocumentId": data.terminus_document_id,
    }

    with httpx.Client(timeout=settings.EXCHANGE_TIMEOUT) as client:
        response = client.post(
            url,
            json={"query": CREATE_OFFER_MUTATION, "variables": {"input": payload}},
            headers={"Content-Type": "application/json"},
        )
        response.raise_for_status()
        result = response.json()
        if "errors" in result:
            return CreateOfferInExchangeResult(success=False, offer_uuid=data.offer_uuid, message=str(result["errors"]))
        mutation_result = result.get("data", {}).get("createOfferFromWorkflow", {})
        if not mutation_result.get("success"):
            return CreateOfferInExchangeResult(
                success=False,
                offer_uuid=data.offer_uuid,
                message=mutation_result.get("message", "Unknown error"),
            )

    return CreateOfferInExchangeResult(success=True, offer_uuid=data.offer_uuid)


@activity.defn(name="update_offer_workflow_status")
def update_offer_workflow_status(data: UpdateOfferWorkflowStatusInput) -> UpdateOfferWorkflowStatusResult:
    url = f"http://{settings.EXCHANGE_INTERNAL_URL}/graphql/m2m/"

    payload = {
        "offerUuid": data.offer_uuid,
        "status": data.status,
        "errorMessage": data.error_message,
    }

    with httpx.Client(timeout=settings.EXCHANGE_TIMEOUT) as client:
        response = client.post(
            url,
            json={"query": UPDATE_OFFER_STATUS_MUTATION, "variables": {"input": payload}},
            headers={"Content-Type": "application/json"},
        )
        response.raise_for_status()
        result = response.json()
        if "errors" in result:
            return UpdateOfferWorkflowStatusResult(success=False, message=str(result["errors"]))
        mutation_result = result.get("data", {}).get("updateOfferWorkflowStatus", {})
        if not mutation_result.get("success"):
            return UpdateOfferWorkflowStatusResult(success=False, message=mutation_result.get("message", "Unknown error"))

    return UpdateOfferWorkflowStatusResult(success=True, message="OK")
