import { gql } from '@apollo/client'

// ========== GOODS SUPPLY V2 MUTATIONS (ЗАКОММЕНТИРОВАНО) ==========
// Раскомментируйте для активации системы товарных поставок V2

// ========== V2 MUTATIONS START ==========
// V2 GraphQL mutations АКТИВИРОВАНЫ

export const CREATE_GOODS_SUPPLY_ORDER_V2 = gql`
  mutation CreateGoodsSupplyOrder($input: CreateGoodsSupplyOrderInput!) {
    createGoodsSupplyOrder(input: $input) {
      success
      message
      order {
        id
        status
        sellerId
        seller {
          id
          name
        }
        fulfillmentCenterId
        fulfillmentCenter {
          id
          name
        }
        requestedDeliveryDate
        totalAmount
        totalItems
        items {
          id
          productId
          product {
            id
            name
            article
          }
          quantity
          price
          totalPrice
          recipe {
            id
            totalCost
          }
        }
        requestedServices {
          id
          serviceId
          service {
            id
            name
          }
          quantity
          price
          totalPrice
        }
        createdAt
      }
    }
  }
`

export const UPDATE_GOODS_SUPPLY_ORDER_STATUS_V2 = gql`
  mutation UpdateGoodsSupplyOrderStatus(
    $id: ID!
    $status: GoodsSupplyOrderStatus!
    $notes: String
  ) {
    updateGoodsSupplyOrderStatus(id: $id, status: $status, notes: $notes) {
      id
      status
      notes
      
      # Обновленные поля в зависимости от статуса
      supplierApprovedAt
      shippedAt
      receivedAt
      receivedBy {
        id
        firstName
        lastName
      }
      
      updatedAt
    }
  }
`

export const RECEIVE_GOODS_SUPPLY_ORDER_V2 = gql`
  mutation ReceiveGoodsSupplyOrder(
    $id: ID!
    $items: [ReceiveGoodsItemInput!]!
  ) {
    receiveGoodsSupplyOrder(id: $id, items: $items) {
      id
      status
      receivedAt
      receivedBy {
        id
        firstName
        lastName
      }
      
      # Обновленные товары с данными приемки
      items {
        id
        productId
        product {
          id
          name
          article
        }
        quantity
        receivedQuantity
        damagedQuantity
        acceptanceNotes
        
        # Обновленные данные рецептуры после приемки
        recipe {
          id
          components {
            id
            materialId
            material {
              id
              name
              currentStock  # обновленный остаток после использования
            }
            quantity
          }
        }
      }
      
      # Обновленные услуги
      requestedServices {
        id
        serviceId
        service {
          id
          name
        }
        status
        quantity
      }
      
      updatedAt
    }
  }
`

export const CANCEL_GOODS_SUPPLY_ORDER_V2 = gql`
  mutation CancelGoodsSupplyOrder($id: ID!, $reason: String!) {
    cancelGoodsSupplyOrder(id: $id, reason: $reason) {
      id
      status
      notes
      updatedAt
    }
  }
`

export const UPSERT_PRODUCT_RECIPE_V2 = gql`
  mutation UpsertProductRecipe(
    $productId: ID!
    $components: [RecipeComponentInput!]!
    $services: [RecipeServiceInput!]!
  ) {
    upsertProductRecipe(
      productId: $productId
      components: $components
      services: $services
    ) {
      id
      productId
      product {
        id
        name
        article
      }
      
      components {
        id
        materialId
        material {
          id
          name
          unit
          price
          currentStock
        }
        quantity
        unit
        cost
      }
      
      services {
        id
        serviceId
        service {
          id
          name
          price
          unit
        }
        quantity
        price
        totalPrice
      }
      
      totalCost
      updatedAt
    }
  }
`

// Дополнительные мутации для управления услугами
export const UPDATE_SERVICE_REQUEST_STATUS_V2 = gql`
  mutation UpdateServiceRequestStatus(
    $id: ID!
    $status: ServiceRequestStatus!
  ) {
    updateServiceRequestStatus(id: $id, status: $status) {
      id
      status
      completedAt
      completedBy {
        id
        firstName
        lastName
      }
      
      # Связанная поставка
      orderId
      order {
        id
        status
        totalItems
        
        # Проверяем готовность всех услуг
        requestedServices {
          id
          status
        }
      }
    }
  }
`

// Мутация для логистических операций
export const ASSIGN_LOGISTICS_TO_GOODS_ORDER_V2 = gql`
  mutation AssignLogisticsToGoodsOrder(
    $orderId: ID!
    $logisticsPartnerId: ID!
    $routeId: ID
    $estimatedDeliveryDate: DateTime!
    $logisticsCost: Float
  ) {
    assignLogisticsToGoodsOrder(
      orderId: $orderId
      logisticsPartnerId: $logisticsPartnerId
      routeId: $routeId
      estimatedDeliveryDate: $estimatedDeliveryDate
      logisticsCost: $logisticsCost
    ) {
      id
      status
      
      logisticsPartnerId
      logisticsPartner {
        id
        name
        phones { value isPrimary }
      }
      routeId
      estimatedDeliveryDate
      logisticsCost
      
      updatedAt
    }
  }
`

// Мутация для поставщика (одобрение заказа)
export const APPROVE_GOODS_SUPPLY_REQUEST_V2 = gql`
  mutation ApproveGoodsSupplyRequest(
    $id: ID!
    $packagesCount: Int!
    $estimatedVolume: Float!
    $notes: String
  ) {
    approveGoodsSupplyRequest(
      id: $id
      packagesCount: $packagesCount
      estimatedVolume: $estimatedVolume
      notes: $notes
    ) {
      id
      status
      supplierApprovedAt
      packagesCount
      estimatedVolume
      notes
      
      # Селлер получит уведомление
      seller {
        id
        name
      }
      
      # Товары с подтвержденными ценами
      items {
        id
        productId
        product {
          id
          name
          price  # цена поставщика
        }
        quantity
        price
        totalPrice
      }
      
      totalAmount
      updatedAt
    }
  }
`

// ========== V2 MUTATIONS END ==========

// Временная обратная совместимость
export const CREATE_GOODS_SUPPLY_ORDER = 'CREATE_SUPPLY_ORDER_LEGACY'