import { gql } from 'graphql-tag'

// Запрос для получения заявок покупателей на возврат от Wildberries
export const GET_WB_RETURN_CLAIMS = gql`
  query GetWbReturnClaims($isArchive: Boolean!, $limit: Int, $offset: Int) {
    wbReturnClaims(isArchive: $isArchive, limit: $limit, offset: $offset) {
      claims {
        id
        claimType
        status
        statusEx
        nmId
        userComment
        wbComment
        dt
        imtName
        orderDt
        dtUpdate
        photos
        videoPaths
        actions
        price
        currencyCode
        srid
        sellerOrganization {
          id
          name
          inn
        }
      }
      total
    }
  }
`

export const GET_ME = gql`
  query GetMe {
    me {
      id
      phone
      avatar
      managerName
      createdAt
      organization {
        id
        inn
        kpp
        name
        fullName
        address
        addressFull
        ogrn
        ogrnDate
        type
        market
        status
        actualityDate
        registrationDate
        liquidationDate
        managementName
        managementPost
        opfCode
        opfFull
        opfShort
        okato
        oktmo
        okpo
        okved
        employeeCount
        revenue
        taxSystem
        phones
        emails
        apiKeys {
          id
          marketplace
          apiKey
          isActive
          validationData
          createdAt
          updatedAt
        }
      }
    }
  }
`

export const GET_MY_SERVICES = gql`
  query GetMyServices {
    myServices {
      id
      name
      description
      price
      imageUrl
      createdAt
      updatedAt
    }
  }
`

export const GET_MY_SUPPLIES = gql`
  query GetMySupplies {
    mySupplies {
      id
      name
      description
      pricePerUnit
      unit
      imageUrl
      warehouseStock
      isAvailable
      warehouseConsumableId
      createdAt
      updatedAt
      organization {
        id
        name
      }
    }
  }
`

// Новый запрос для получения доступных расходников для рецептур селлеров
export const GET_AVAILABLE_SUPPLIES_FOR_RECIPE = gql`
  query GetAvailableSuppliesForRecipe {
    getAvailableSuppliesForRecipe {
      id
      name
      pricePerUnit
      unit
      imageUrl
      warehouseStock
    }
  }
`

// Получение карточек Wildberries для селекта
export const GET_MY_WILDBERRIES_CARDS = gql`
  query GetMyWildberriesCards {
    myWildberriesSupplies {
      id
      cards {
        id
        nmId
        vendorCode
        title
        brand
        mediaFiles
        price
      }
    }
  }
`

export const GET_MY_FULFILLMENT_SUPPLIES = gql`
  query GetMyFulfillmentSupplies {
    myFulfillmentSupplies {
      id
      name
      article
      description
      price
      quantity
      unit
      category
      status
      date
      supplier
      minStock
      currentStock
      usedStock
      imageUrl
      productId
      createdAt
      updatedAt
    }
  }
`

export const GET_SELLER_SUPPLIES_ON_WAREHOUSE = gql`
  query GetSellerSuppliesOnWarehouse {
    sellerSuppliesOnWarehouse {
      id
      name
      description
      price
      quantity
      unit
      category
      status
      date
      supplier
      minStock
      currentStock
      usedStock
      imageUrl
      type
      shopLocation
      createdAt
      updatedAt
      organization {
        id
        name
        fullName
        type
      }
      sellerOwner {
        id
        name
        fullName
        inn
        type
      }
    }
  }
`

export const GET_MY_LOGISTICS = gql`
  query GetMyLogistics {
    myLogistics {
      id
      fromLocation
      toLocation
      priceUnder1m3
      priceOver1m3
      description
      createdAt
      updatedAt
      organization {
        id
        name
        fullName
      }
    }
  }
`

export const GET_LOGISTICS_PARTNERS = gql`
  query GetLogisticsPartners {
    logisticsPartners {
      id
      name
      fullName
      type
      address
      phones
      emails
    }
  }
`

export const GET_MY_PRODUCTS = gql`
  query GetMyProducts {
    myProducts {
      id
      name
      article
      description
      price
      pricePerSet
      quantity
      setQuantity
      ordered
      inTransit
      stock
      sold
      type
      category {
        id
        name
      }
      brand
      color
      size
      weight
      dimensions
      material
      images
      mainImage
      isActive
      createdAt
      updatedAt
      organization {
        id
        market
      }
    }
  }
`

export const GET_WAREHOUSE_PRODUCTS = gql`
  query GetWarehouseProducts {
    warehouseProducts {
      id
      name
      article
      description
      price
      quantity
      type
      category {
        id
        name
      }
      brand
      color
      size
      weight
      dimensions
      material
      images
      mainImage
      isActive
      organization {
        id
        name
        fullName
      }
      createdAt
      updatedAt
    }
  }
`

// Запросы для контрагентов
export const SEARCH_ORGANIZATIONS = gql`
  query SearchOrganizations($type: OrganizationType, $search: String) {
    searchOrganizations(type: $type, search: $search) {
      id
      inn
      name
      fullName
      type
      address
      phones
      emails
      createdAt
      isCounterparty
      isCurrentUser
      hasOutgoingRequest
      hasIncomingRequest
      users {
        id
        avatar
        managerName
      }
    }
  }
`

export const GET_MY_COUNTERPARTIES = gql`
  query GetMyCounterparties {
    myCounterparties {
      id
      inn
      name
      fullName
      managementName
      type
      address
      market
      phones
      emails
      createdAt
      users {
        id
        avatar
        managerName
      }
    }
  }
`

export const GET_SUPPLY_SUPPLIERS = gql`
  query GetSupplySuppliers {
    supplySuppliers {
      id
      name
      contactName
      phone
      market
      address
      place
      telegram
      createdAt
    }
  }
`

export const GET_ORGANIZATION_LOGISTICS = gql`
  query GetOrganizationLogistics($organizationId: ID!) {
    organizationLogistics(organizationId: $organizationId) {
      id
      fromLocation
      toLocation
      priceUnder1m3
      priceOver1m3
      description
    }
  }
`

export const GET_INCOMING_REQUESTS = gql`
  query GetIncomingRequests {
    incomingRequests {
      id
      status
      message
      createdAt
      sender {
        id
        inn
        name
        fullName
        type
        address
        phones
        emails
        createdAt
        users {
          id
          avatar
        }
      }
      receiver {
        id
        inn
        name
        fullName
        type
        users {
          id
          avatar
        }
      }
    }
  }
`

export const GET_OUTGOING_REQUESTS = gql`
  query GetOutgoingRequests {
    outgoingRequests {
      id
      status
      message
      createdAt
      sender {
        id
        inn
        name
        fullName
        type
        users {
          id
          avatar
        }
      }
      receiver {
        id
        inn
        name
        fullName
        type
        address
        phones
        emails
        createdAt
        users {
          id
          avatar
        }
      }
    }
  }
`

export const GET_ORGANIZATION = gql`
  query GetOrganization($id: ID!) {
    organization(id: $id) {
      id
      inn
      name
      fullName
      address
      type
      apiKeys {
        id
        marketplace
        apiKey
        isActive
        validationData
        createdAt
        updatedAt
      }
      createdAt
      updatedAt
    }
  }
`

// Запросы для сообщений
export const GET_MESSAGES = gql`
  query GetMessages($counterpartyId: ID!, $limit: Int, $offset: Int) {
    messages(counterpartyId: $counterpartyId, limit: $limit, offset: $offset) {
      id
      content
      type
      voiceUrl
      voiceDuration
      fileUrl
      fileName
      fileSize
      fileType
      senderId
      senderOrganization {
        id
        name
        fullName
        type
        users {
          id
          avatar
          managerName
        }
      }
      receiverOrganization {
        id
        name
        fullName
        type
        users {
          id
          avatar
          managerName
        }
      }
      isRead
      createdAt
      updatedAt
    }
  }
`

export const GET_CONVERSATIONS = gql`
  query GetConversations {
    conversations {
      id
      counterparty {
        id
        inn
        name
        fullName
        type
        address
        users {
          id
          avatar
          managerName
        }
      }
      lastMessage {
        id
        content
        type
        voiceUrl
        voiceDuration
        fileUrl
        fileName
        fileSize
        fileType
        senderId
        isRead
        createdAt
      }
      unreadCount
      updatedAt
    }
  }
`

export const GET_CATEGORIES = gql`
  query GetCategories {
    categories {
      id
      name
      createdAt
      updatedAt
    }
  }
`

export const GET_ALL_PRODUCTS = gql`
  query GetAllProducts($search: String, $category: String) {
    allProducts(search: $search, category: $category) {
      id
      name
      article
      description
      price
      quantity
      type
      category {
        id
        name
      }
      brand
      color
      size
      weight
      dimensions
      material
      images
      mainImage
      isActive
      createdAt
      updatedAt
      organization {
        id
        inn
        name
        fullName
        type
        address
        phones
        emails
        users {
          id
          avatar
          managerName
        }
      }
    }
  }
`

// Запрос товаров конкретной организации (для формы создания поставки)
export const GET_ORGANIZATION_PRODUCTS = gql`
  query GetOrganizationProducts($organizationId: ID!, $search: String, $category: String, $type: String) {
    organizationProducts(organizationId: $organizationId, search: $search, category: $category, type: $type) {
      id
      name
      article
      description
      price
      quantity
      type
      category {
        id
        name
      }
      brand
      color
      size
      weight
      dimensions
      material
      images
      mainImage
      isActive
      createdAt
      updatedAt
      organization {
        id
        inn
        name
        fullName
        type
        address
        phones
        emails
        users {
          id
          avatar
          managerName
        }
      }
    }
  }
`

export const GET_MY_CART = gql`
  query GetMyCart {
    myCart {
      id
      totalPrice
      totalItems
      items {
        id
        quantity
        totalPrice
        isAvailable
        availableQuantity
        createdAt
        updatedAt
        product {
          id
          name
          article
          description
          price
          quantity
          brand
          color
          size
          images
          mainImage
          isActive
          category {
            id
            name
          }
          organization {
            id
            inn
            name
            fullName
            type
            address
            phones
            emails
            users {
              id
              avatar
              managerName
            }
          }
        }
      }
      createdAt
      updatedAt
    }
  }
`

export const GET_MY_FAVORITES = gql`
  query GetMyFavorites {
    myFavorites {
      id
      name
      article
      description
      price
      quantity
      brand
      color
      size
      images
      mainImage
      isActive
      createdAt
      updatedAt
      category {
        id
        name
      }
      organization {
        id
        inn
        name
        fullName
        type
        address
        phones
        emails
        users {
          id
          avatar
          managerName
        }
      }
    }
  }
`

// Запросы для сотрудников
export const GET_MY_EMPLOYEES = gql`
  query GetMyEmployees {
    myEmployees {
      id
      firstName
      lastName
      middleName
      fullName
      name
      birthDate
      avatar
      passportSeries
      passportNumber
      passportIssued
      passportDate
      address
      position
      department
      hireDate
      salary
      status
      phone
      email
      telegram
      whatsapp
      passportPhoto
      emergencyContact
      emergencyPhone
      createdAt
      updatedAt
    }
  }
`

export const GET_EMPLOYEE = gql`
  query GetEmployee($id: ID!) {
    employee(id: $id) {
      id
      firstName
      lastName
      middleName
      birthDate
      avatar
      passportSeries
      passportNumber
      passportIssued
      passportDate
      address
      position
      department
      hireDate
      salary
      status
      phone
      email
      emergencyContact
      emergencyPhone
      createdAt
      updatedAt
    }
  }
`

export const GET_EMPLOYEE_SCHEDULE = gql`
  query GetEmployeeSchedule($employeeId: ID!, $year: Int!, $month: Int!) {
    employeeSchedule(employeeId: $employeeId, year: $year, month: $month) {
      id
      date
      status
      hoursWorked
      notes
      employee {
        id
      }
    }
  }
`

export const GET_MY_WILDBERRIES_SUPPLIES = gql`
  query GetMyWildberriesSupplies {
    myWildberriesSupplies {
      id
      deliveryDate
      status
      totalAmount
      totalItems
      createdAt
      cards {
        id
        nmId
        vendorCode
        title
        brand
        price
        discountedPrice
        quantity
        selectedQuantity
        selectedMarket
        selectedPlace
        sellerName
        sellerPhone
        deliveryDate
        mediaFiles
        selectedServices
      }
    }
  }
`

// Запросы для получения услуг и расходников от конкретных организаций-контрагентов
export const GET_COUNTERPARTY_SERVICES = gql`
  query GetCounterpartyServices($organizationId: ID!) {
    counterpartyServices(organizationId: $organizationId) {
      id
      name
      description
      price
      imageUrl
      createdAt
      updatedAt
    }
  }
`

export const GET_COUNTERPARTY_SUPPLIES = gql`
  query GetCounterpartySupplies($organizationId: ID!) {
    counterpartySupplies(organizationId: $organizationId) {
      id
      name
      description
      price
      quantity
      unit
      category
      status
      imageUrl
      createdAt
      updatedAt
    }
  }
`

// Wildberries запросы
export const GET_WILDBERRIES_STATISTICS = gql`
  query GetWildberriesStatistics($period: String, $startDate: String, $endDate: String) {
    getWildberriesStatistics(period: $period, startDate: $startDate, endDate: $endDate) {
      success
      message
      data {
        date
        sales
        orders
        advertising
        refusals
        returns
        revenue
        buyoutPercentage
      }
    }
  }
`

export const GET_WILDBERRIES_CAMPAIGN_STATS = gql`
  query GetWildberriesCampaignStats($input: WildberriesCampaignStatsInput!) {
    getWildberriesCampaignStats(input: $input) {
      success
      message
      data {
        advertId
        views
        clicks
        ctr
        cpc
        sum
        atbs
        orders
        cr
        shks
        sum_price
        interval {
          begin
          end
        }
        days {
          date
          views
          clicks
          ctr
          cpc
          sum
          atbs
          orders
          cr
          shks
          sum_price
          apps {
            views
            clicks
            ctr
            cpc
            sum
            atbs
            orders
            cr
            shks
            sum_price
            appType
            nm {
              views
              clicks
              ctr
              cpc
              sum
              atbs
              orders
              cr
              shks
              sum_price
              name
              nmId
            }
          }
        }
        boosterStats {
          date
          nm
          avg_position
        }
      }
    }
  }
`

export const GET_WILDBERRIES_CAMPAIGNS_LIST = gql`
  query GetWildberriesCampaignsList {
    getWildberriesCampaignsList {
      success
      message
      data {
        adverts {
          type
          status
          count
          advert_list {
            advertId
            changeTime
          }
        }
        all
      }
    }
  }
`

export const GET_EXTERNAL_ADS = gql`
  query GetExternalAds($dateFrom: String!, $dateTo: String!) {
    getExternalAds(dateFrom: $dateFrom, dateTo: $dateTo) {
      success
      message
      externalAds {
        id
        name
        url
        cost
        date
        nmId
        clicks
        organizationId
        createdAt
        updatedAt
      }
    }
  }
`

// Админ запросы
export const ADMIN_ME = gql`
  query AdminMe {
    adminMe {
      id
      username
      email
      isActive
      lastLogin
      createdAt
      updatedAt
    }
  }
`

export const ALL_USERS = gql`
  query AllUsers($search: String, $limit: Int, $offset: Int) {
    allUsers(search: $search, limit: $limit, offset: $offset) {
      users {
        id
        phone
        managerName
        avatar
        createdAt
        updatedAt
        organization {
          id
          inn
          name
          fullName
          type
          status
          createdAt
        }
      }
      total
      hasMore
    }
  }
`

export const GET_SUPPLY_ORDERS = gql`
  query GetSupplyOrders {
    supplyOrders {
      id
      organizationId
      partnerId
      deliveryDate
      status
      totalAmount
      totalItems
      fulfillmentCenterId
      consumableType
      createdAt
      updatedAt
      partner {
        id
        name
        fullName
        inn
        address
        phones
        emails
      }
      organization {
        id
        name
        fullName
        type
      }
      fulfillmentCenter {
        id
        name
        fullName
        type
      }
      logisticsPartner {
        id
        name
        fullName
        type
      }
      items {
        id
        quantity
        price
        totalPrice
        recipe {
          services {
            id
            name
          }
          fulfillmentConsumables {
            id
            name
          }
          sellerConsumables {
            id
            name
          }
          marketplaceCardId
        }
        product {
          id
          name
          article
          description
          price
          quantity
          images
          mainImage
          category {
            id
            name
          }
        }
      }
    }
  }
`

export const GET_PENDING_SUPPLIES_COUNT = gql`
  query GetPendingSuppliesCount {
    pendingSuppliesCount {
      supplyOrders
      ourSupplyOrders
      sellerSupplyOrders
      incomingSupplierOrders
      incomingRequests
      total
    }
  }
`

// Запрос данных склада с партнерами (включая автосозданные записи)
export const GET_WAREHOUSE_DATA = gql`
  query GetWarehouseData {
    warehouseData {
      stores {
        id
        storeName
        storeOwner
        storeImage
        storeQuantity
        partnershipDate
        products {
          id
          productName
          productQuantity
          productPlace
          variants {
            id
            variantName
            variantQuantity
            variantPlace
          }
        }
      }
    }
  }
`

// Запросы для кеша склада WB
export const GET_WB_WAREHOUSE_DATA = gql`
  query GetWBWarehouseData {
    getWBWarehouseData {
      success
      message
      fromCache
      cache {
        id
        organizationId
        cacheDate
        data
        totalProducts
        totalStocks
        totalReserved
        createdAt
        updatedAt
      }
    }
  }
`

// Запросы для кеша статистики продаж
export const GET_SELLER_STATS_CACHE = gql`
  query GetSellerStatsCache($period: String!, $dateFrom: String, $dateTo: String) {
    getSellerStatsCache(period: $period, dateFrom: $dateFrom, dateTo: $dateTo) {
      success
      message
      fromCache
      cache {
        id
        organizationId
        cacheDate
        period
        dateFrom
        dateTo
        productsData
        productsTotalSales
        productsTotalOrders
        productsCount
        advertisingData
        advertisingTotalCost
        advertisingTotalViews
        advertisingTotalClicks
        expiresAt
        createdAt
        updatedAt
      }
    }
  }
`

// Запрос для получения статистики склада фулфилмента с изменениями за сутки
export const GET_FULFILLMENT_WAREHOUSE_STATS = gql`
  query GetFulfillmentWarehouseStats {
    fulfillmentWarehouseStats {
      products {
        current
        change
        percentChange
      }
      goods {
        current
        change
        percentChange
      }
      defects {
        current
        change
        percentChange
      }
      pvzReturns {
        current
        change
        percentChange
      }
      fulfillmentSupplies {
        current
        change
        percentChange
      }
      sellerSupplies {
        current
        change
        percentChange
      }
    }
  }
`

// Запрос для получения движений товаров (прибыло/убыло) за период
export const GET_SUPPLY_MOVEMENTS = gql`
  query GetSupplyMovements($period: String = "24h") {
    supplyMovements(period: $period) {
      arrived {
        products
        goods
        defects
        pvzReturns
        fulfillmentSupplies
        sellerSupplies
      }
      departed {
        products
        goods
        defects
        pvzReturns
        fulfillmentSupplies
        sellerSupplies
      }
    }
  }
`

// Запрос партнерской ссылки
export const GET_MY_PARTNER_LINK = gql`
  query GetMyPartnerLink {
    myPartnerLink
  }
`

// Запрос поставок селлера для многоуровневой таблицы
export const GET_MY_SUPPLY_ORDERS = gql`
  query GetMySupplyOrders {
    mySupplyOrders {
      id
      organizationId
      partnerId
      deliveryDate
      status
      totalAmount
      totalItems
      fulfillmentCenterId
      logisticsPartnerId
      packagesCount
      volume
      responsibleEmployee
      notes
      createdAt
      updatedAt
      partner {
        id
        name
        fullName
        inn
        address
        addressFull
        market
        type
        managementName
        phones
        users {
          id
          managerName
          phone
          avatar
        }
      }
      organization {
        id
        name
        fullName
        type
        market
      }
      fulfillmentCenter {
        id
        name
        fullName
        address
        addressFull
        type
      }
      logisticsPartner {
        id
        name
        fullName
        type
      }
      # employee { # Поле не существует в SupplyOrder модели
      #   id
      #   firstName
      #   lastName
      #   middleName
      #   position
      #   avatar
      # }
      # routes { # Поле не существует в SupplyOrder модели
      #   id
      #   logisticsId
      #   fromLocation
      #   toLocation
      #   fromAddress
      #   toAddress
      #   distance
      #   estimatedTime
      #   price
      #   status
      #   createdAt
      #   updatedAt
      #   createdDate
      #   logistics {
      #     id
      #     fromLocation
      #     toLocation
      #     priceUnder1m3
      #     priceOver1m3
      #     description
      #     organization {
      #       id
      #       name
      #       fullName
      #     }
      #   }
      # }
      items {
        id
        quantity
        price
        totalPrice
        productId
        recipe {
          services {
            id
            name
            price
          }
          fulfillmentConsumables {
            id
            name
            price
          }
          sellerConsumables {
            id
            name
            price
          }
          marketplaceCardId
        }
        product {
          id
          name
          article
          description
          price
          quantity
          images
          mainImage
          # unit # Поле не существует в Product типе
          weight
          dimensions
          category {
            id
            name
          }
          organization {
            id
            name
            fullName
            market
          }
          # sizes { # Поле не существует в Product типе
          #   id
          #   name
          #   quantity
          #   price
          # }
        }
      }
    }
  }
`

// Экспорт реферальных запросов
export {
  GET_MY_REFERRAL_LINK,
  GET_MY_REFERRAL_STATS,
  GET_MY_REFERRALS,
  GET_MY_REFERRAL_TRANSACTIONS,
  GET_REFERRAL_DASHBOARD_DATA,
} from './referral-queries'
