import { GraphQLError } from 'graphql'

import { prisma } from '../../../lib/prisma'
import { Context } from '../../context'
import { DomainResolvers } from '../shared/types'

// Services Domain Resolvers - управление услугами фулфилмента (мигрировано из fulfillment-services-v2.ts)

console.warn('🔥 МОДУЛЬ SERVICES DOMAIN ЗАГРУЖАЕТСЯ')

// =============================================================================
// 🔐 AUTHENTICATION HELPERS
// =============================================================================

const withAuth = (resolver: any) => {
  return async (parent: any, args: any, context: Context) => {
    console.log('🔐 SERVICES DOMAIN AUTH CHECK:', { 
      hasUser: !!context.user, 
      userId: context.user?.id,
      organizationId: context.user?.organizationId, 
    })
    if (!context.user) {
      console.error('❌ AUTH FAILED: No user in context')
      throw new GraphQLError('Требуется авторизация', {
        extensions: { code: 'UNAUTHENTICATED' },
      })
    }
    console.log('✅ AUTH PASSED: Calling resolver')
    try {
      const result = await resolver(parent, args, context)
      console.log('🎯 RESOLVER RESULT TYPE:', typeof result, result === null ? 'NULL RESULT!' : 'Has result')
      return result
    } catch (error) {
      console.error('💥 RESOLVER ERROR:', error)
      throw error
    }
  }
}

const checkFulfillmentAccess = async (userId: string) => {
  const user = await prisma.user.findUnique({
    where: { id: userId },
    include: { organization: true },
  })

  if (!user?.organizationId) {
    throw new GraphQLError('Пользователь не привязан к организации', {
      extensions: { code: 'FORBIDDEN' },
    })
  }

  if (!user.organization || user.organization.type !== 'FULFILLMENT') {
    throw new GraphQLError('Только фулфилмент может управлять услугами', {
      extensions: { code: 'FORBIDDEN' },
    })
  }

  return user
}

// =============================================================================
// 🛠️ INTERFACE DEFINITIONS
// =============================================================================

interface CreateFulfillmentServiceInput {
  name: string
  description?: string
  price: number
  unit?: string
  imageUrl?: string
  sortOrder?: number
}

interface UpdateFulfillmentServiceInput {
  id: string
  name?: string
  description?: string
  price?: number
  unit?: string
  imageUrl?: string
  sortOrder?: number
  isActive?: boolean
}

interface CreateFulfillmentConsumableInput {
  name: string
  article?: string
  description?: string
  pricePerUnit: number
  unit?: string
  minStock?: number
  currentStock?: number
  imageUrl?: string
  sortOrder?: number
}

interface UpdateFulfillmentConsumableInput {
  id: string
  name?: string
  nameForSeller?: string
  article?: string
  pricePerUnit?: number
  unit?: string
  minStock?: number
  currentStock?: number
  imageUrl?: string
  sortOrder?: number
  isAvailable?: boolean
}

interface CreateFulfillmentLogisticsInput {
  fromLocation: string
  toLocation: string
  fromAddress?: string
  toAddress?: string
  priceUnder1m3: number
  priceOver1m3: number
  estimatedDays: number
  description?: string
  sortOrder?: number
}

interface UpdateFulfillmentLogisticsInput {
  id: string
  fromLocation?: string
  toLocation?: string
  fromAddress?: string
  toAddress?: string
  priceUnder1m3?: number
  priceOver1m3?: number
  estimatedDays?: number
  description?: string
  sortOrder?: number
  isActive?: boolean
}

// =============================================================================
// 🛠️ SERVICES DOMAIN RESOLVERS
// =============================================================================

export const servicesResolvers: DomainResolvers = {
  Query: {
    // Мои услуги (для фулфилмента)
    myFulfillmentServices: withAuth(async (_: unknown, __: unknown, context: Context) => {
      console.log('🔍 MY_FULFILLMENT_SERVICES DOMAIN QUERY STARTED:', { userId: context.user?.id })
      try {
        const user = await checkFulfillmentAccess(context.user!.id)

        const services = await prisma.fulfillmentService.findMany({
          where: {
            fulfillmentId: user.organizationId!,
          },
          include: {
            fulfillment: true,
          },
          orderBy: [
            { sortOrder: 'asc' },
            { name: 'asc' },
          ],
          take: 200, // Добавляем пагинацию для производительности
        })

        console.log('✅ MY_FULFILLMENT_SERVICES DOMAIN SUCCESS:', { count: services.length })
        return services
      } catch (error) {
        console.error('❌ MY_FULFILLMENT_SERVICES DOMAIN ERROR:', error)
        return []
      }
    }),

    // Мои расходники (для фулфилмента)
    myFulfillmentConsumables: withAuth(async (_: unknown, __: unknown, context: Context) => {
      console.log('🔍 MY_FULFILLMENT_CONSUMABLES DOMAIN QUERY STARTED:', { userId: context.user?.id })
      try {
        const user = await checkFulfillmentAccess(context.user!.id)

        const consumables = await prisma.fulfillmentConsumable.findMany({
          where: {
            fulfillmentId: user.organizationId!,
          },
          include: {
            fulfillment: true,
            inventory: {
              include: {
                product: true,
              },
            },
          },
          orderBy: [
            { sortOrder: 'asc' },
            { name: 'asc' },
          ],
          take: 200, // Добавляем пагинацию для производительности
        })

        console.log('✅ MY_FULFILLMENT_CONSUMABLES DOMAIN SUCCESS:', { 
          count: consumables.length,
          firstThree: consumables.slice(0, 3).map(c => ({ 
            id: c.id, 
            name: c.name, 
            currentStock: c.currentStock,
            isAvailable: c.isAvailable, 
          })),
        })
        return consumables
      } catch (error) {
        console.error('❌ MY_FULFILLMENT_CONSUMABLES DOMAIN ERROR:', error)
        return []
      }
    }),

    // Моя логистика (для фулфилмента)
    myFulfillmentLogistics: withAuth(async (_: unknown, __: unknown, context: Context) => {
      console.log('🔍 MY_FULFILLMENT_LOGISTICS DOMAIN QUERY STARTED:', { userId: context.user?.id })
      try {
        const user = await checkFulfillmentAccess(context.user!.id)

        const logistics = await prisma.fulfillmentLogistics.findMany({
          where: {
            fulfillmentId: user.organizationId!,
          },
          include: {
            fulfillment: true,
          },
          orderBy: [
            { sortOrder: 'asc' },
            { fromLocation: 'asc' },
          ],
          take: 200, // Добавляем пагинацию для производительности
        })

        console.log('✅ MY_FULFILLMENT_LOGISTICS DOMAIN SUCCESS:', { count: logistics.length })
        return logistics
      } catch (error) {
        console.error('❌ MY_FULFILLMENT_LOGISTICS DOMAIN ERROR:', error)
        return []
      }
    }),

    // Услуги конкретного фулфилмента (для селлеров при создании поставки)
    fulfillmentServicesById: withAuth(async (_: unknown, args: { fulfillmentId: string }, context: Context) => {
      console.log('🔍 FULFILLMENT_SERVICES_BY_ID DOMAIN QUERY STARTED:', { 
        userId: context.user?.id,
        fulfillmentId: args.fulfillmentId,
      })
      try {
        const services = await prisma.fulfillmentService.findMany({
          where: {
            fulfillmentId: args.fulfillmentId,
            isActive: true,
          },
          include: {
            fulfillment: true,
          },
          orderBy: [
            { sortOrder: 'asc' },
            { name: 'asc' },
          ],
        })

        console.log('✅ FULFILLMENT_SERVICES_BY_ID DOMAIN SUCCESS:', { count: services.length })
        return services
      } catch (error) {
        console.error('❌ FULFILLMENT_SERVICES_BY_ID DOMAIN ERROR:', error)
        return []
      }
    }),

    // Расходники конкретного фулфилмента (для селлеров при создании поставки)
    fulfillmentConsumablesById: withAuth(async (_: unknown, args: { fulfillmentId: string }, context: Context) => {
      console.log('🔍 FULFILLMENT_CONSUMABLES_BY_ID DOMAIN QUERY STARTED:', { 
        userId: context.user?.id,
        fulfillmentId: args.fulfillmentId,
      })
      try {
        const consumables = await prisma.fulfillmentConsumable.findMany({
          where: {
            fulfillmentId: args.fulfillmentId,
            isAvailable: true,
          },
          include: {
            fulfillment: true,
          },
          orderBy: [
            { sortOrder: 'asc' },
            { name: 'asc' },
          ],
        })

        console.log('✅ FULFILLMENT_CONSUMABLES_BY_ID DOMAIN SUCCESS:', { count: consumables.length })
        return consumables
      } catch (error) {
        console.error('❌ FULFILLMENT_CONSUMABLES_BY_ID DOMAIN ERROR:', error)
        return []
      }
    }),
  },

  Mutation: {
    // =============================================================================
    // 🔧 МУТАЦИИ ДЛЯ УСЛУГ ФУЛФИЛМЕНТА
    // =============================================================================

    // Создание услуги
    createFulfillmentService: withAuth(async (
      _: unknown,
      args: { input: CreateFulfillmentServiceInput },
      context: Context,
    ) => {
      console.log('🔍 CREATE_FULFILLMENT_SERVICE DOMAIN MUTATION STARTED:', { userId: context.user?.id })
      try {
        const user = await checkFulfillmentAccess(context.user!.id)

        const service = await prisma.fulfillmentService.create({
          data: {
            fulfillmentId: user.organizationId!,
            name: args.input.name,
            description: args.input.description,
            price: args.input.price,
            unit: args.input.unit || 'шт',
            imageUrl: args.input.imageUrl,
            sortOrder: args.input.sortOrder || 0,
            isActive: true,
          },
          include: {
            fulfillment: true,
          },
        })

        const result = {
          success: true,
          message: 'Услуга успешно создана',
          service,
        }
        console.log('✅ CREATE_FULFILLMENT_SERVICE DOMAIN SUCCESS:', { serviceId: service.id })
        return result
      } catch (error: any) {
        console.error('❌ CREATE_FULFILLMENT_SERVICE DOMAIN ERROR:', error)
        return {
          success: false,
          message: `Ошибка при создании услуги: ${error.message}`,
          service: null,
        }
      }
    }),

    // Обновление услуги
    updateFulfillmentService: withAuth(async (
      _: unknown,
      args: { input: UpdateFulfillmentServiceInput },
      context: Context,
    ) => {
      console.log('🔍 UPDATE_FULFILLMENT_SERVICE DOMAIN MUTATION STARTED:', { 
        userId: context.user?.id,
        serviceId: args.input.id,
      })
      try {
        const user = await checkFulfillmentAccess(context.user!.id)

        // Проверяем что услуга принадлежит текущему фулфилменту
        const existingService = await prisma.fulfillmentService.findFirst({
          where: {
            id: args.input.id,
            fulfillmentId: user.organizationId!,
          },
        })

        if (!existingService) {
          return {
            success: false,
            message: 'Услуга не найдена или не принадлежит вашей организации',
            service: null,
          }
        }

        const updateData: any = {}
        if (args.input.name !== undefined) updateData.name = args.input.name
        if (args.input.description !== undefined) updateData.description = args.input.description
        if (args.input.price !== undefined) updateData.price = args.input.price
        if (args.input.unit !== undefined) updateData.unit = args.input.unit
        if (args.input.imageUrl !== undefined) updateData.imageUrl = args.input.imageUrl
        if (args.input.sortOrder !== undefined) updateData.sortOrder = args.input.sortOrder
        if (args.input.isActive !== undefined) updateData.isActive = args.input.isActive

        const service = await prisma.fulfillmentService.update({
          where: { id: args.input.id },
          data: updateData,
          include: {
            fulfillment: true,
          },
        })

        const result = {
          success: true,
          message: 'Услуга успешно обновлена',
          service,
        }
        console.log('✅ UPDATE_FULFILLMENT_SERVICE DOMAIN SUCCESS:', { serviceId: service.id })
        return result
      } catch (error: any) {
        console.error('❌ UPDATE_FULFILLMENT_SERVICE DOMAIN ERROR:', error)
        return {
          success: false,
          message: `Ошибка при обновлении услуги: ${error.message}`,
          service: null,
        }
      }
    }),

    // Удаление услуги
    deleteFulfillmentService: withAuth(async (_: unknown, args: { id: string }, context: Context) => {
      console.log('🔍 DELETE_FULFILLMENT_SERVICE DOMAIN MUTATION STARTED:', { 
        userId: context.user?.id,
        serviceId: args.id,
      })
      try {
        const user = await checkFulfillmentAccess(context.user!.id)

        // Проверяем что услуга принадлежит текущему фулфилменту
        const existingService = await prisma.fulfillmentService.findFirst({
          where: {
            id: args.id,
            fulfillmentId: user.organizationId!,
          },
        })

        if (!existingService) {
          throw new GraphQLError('Услуга не найдена или не принадлежит вашей организации')
        }

        await prisma.fulfillmentService.delete({
          where: { id: args.id },
        })

        console.log('✅ DELETE_FULFILLMENT_SERVICE DOMAIN SUCCESS:', { serviceId: args.id })
        return true
      } catch (error: any) {
        console.error('❌ DELETE_FULFILLMENT_SERVICE DOMAIN ERROR:', error)
        throw new GraphQLError(`Ошибка при удалении услуги: ${error.message}`)
      }
    }),

    // =============================================================================
    // 📦 МУТАЦИИ ДЛЯ РАСХОДНИКОВ ФУЛФИЛМЕНТА
    // =============================================================================

    // Создание расходника
    createFulfillmentConsumable: withAuth(async (
      _: unknown,
      args: { input: CreateFulfillmentConsumableInput },
      context: Context,
    ) => {
      console.log('🔍 CREATE_FULFILLMENT_CONSUMABLE DOMAIN MUTATION STARTED:', { userId: context.user?.id })
      try {
        const user = await checkFulfillmentAccess(context.user!.id)

        const consumable = await prisma.fulfillmentConsumable.create({
          data: {
            fulfillmentId: user.organizationId!,
            name: args.input.name,
            article: args.input.article,
            description: args.input.description,
            pricePerUnit: args.input.pricePerUnit,
            unit: args.input.unit || 'шт',
            minStock: args.input.minStock || 0,
            currentStock: args.input.currentStock || 0,
            isAvailable: (args.input.currentStock || 0) > 0,
            imageUrl: args.input.imageUrl,
            sortOrder: args.input.sortOrder || 0,
          },
          include: {
            fulfillment: true,
          },
        })

        const result = {
          success: true,
          message: 'Расходник успешно создан',
          consumable,
        }
        console.log('✅ CREATE_FULFILLMENT_CONSUMABLE DOMAIN SUCCESS:', { consumableId: consumable.id })
        return result
      } catch (error: any) {
        console.error('❌ CREATE_FULFILLMENT_CONSUMABLE DOMAIN ERROR:', error)
        return {
          success: false,
          message: `Ошибка при создании расходника: ${error.message}`,
          consumable: null,
        }
      }
    }),

    // Обновление расходника
    updateFulfillmentConsumable: withAuth(async (
      _: unknown,
      args: { input: UpdateFulfillmentConsumableInput },
      context: Context,
    ) => {
      console.log('🔍 UPDATE_FULFILLMENT_CONSUMABLE DOMAIN MUTATION STARTED:', { 
        userId: context.user?.id,
        consumableId: args.input.id,
      })
      try {
        const user = await checkFulfillmentAccess(context.user!.id)

        // Проверяем что расходник принадлежит текущему фулфилменту
        const existingConsumable = await prisma.fulfillmentConsumable.findFirst({
          where: {
            id: args.input.id,
            fulfillmentId: user.organizationId!,
          },
        })

        if (!existingConsumable) {
          return {
            success: false,
            message: 'Расходник не найден или не принадлежит вашей организации',
            consumable: null,
          }
        }

        const updateData: any = {}
        if (args.input.name !== undefined) updateData.name = args.input.name
        if (args.input.nameForSeller !== undefined) updateData.nameForSeller = args.input.nameForSeller
        if (args.input.article !== undefined) updateData.article = args.input.article
        if (args.input.pricePerUnit !== undefined) updateData.pricePerUnit = args.input.pricePerUnit
        if (args.input.unit !== undefined) updateData.unit = args.input.unit
        if (args.input.minStock !== undefined) updateData.minStock = args.input.minStock
        if (args.input.currentStock !== undefined) {
          updateData.currentStock = args.input.currentStock
          updateData.isAvailable = args.input.currentStock > 0
        }
        if (args.input.imageUrl !== undefined) updateData.imageUrl = args.input.imageUrl
        if (args.input.sortOrder !== undefined) updateData.sortOrder = args.input.sortOrder
        if (args.input.isAvailable !== undefined) updateData.isAvailable = args.input.isAvailable

        const consumable = await prisma.fulfillmentConsumable.update({
          where: { id: args.input.id },
          data: updateData,
          include: {
            fulfillment: true,
          },
        })

        const result = {
          success: true,
          message: 'Расходник успешно обновлен',
          consumable,
        }
        console.log('✅ UPDATE_FULFILLMENT_CONSUMABLE DOMAIN SUCCESS:', { consumableId: consumable.id })
        return result
      } catch (error: any) {
        console.error('❌ UPDATE_FULFILLMENT_CONSUMABLE DOMAIN ERROR:', error)
        return {
          success: false,
          message: `Ошибка при обновлении расходника: ${error.message}`,
          consumable: null,
        }
      }
    }),

    // Удаление расходника
    deleteFulfillmentConsumable: withAuth(async (_: unknown, args: { id: string }, context: Context) => {
      console.log('🔍 DELETE_FULFILLMENT_CONSUMABLE DOMAIN MUTATION STARTED:', { 
        userId: context.user?.id,
        consumableId: args.id,
      })
      try {
        const user = await checkFulfillmentAccess(context.user!.id)

        // Проверяем что расходник принадлежит текущему фулфилменту
        const existingConsumable = await prisma.fulfillmentConsumable.findFirst({
          where: {
            id: args.id,
            fulfillmentId: user.organizationId!,
          },
        })

        if (!existingConsumable) {
          throw new GraphQLError('Расходник не найден или не принадлежит вашей организации')
        }

        await prisma.fulfillmentConsumable.delete({
          where: { id: args.id },
        })

        console.log('✅ DELETE_FULFILLMENT_CONSUMABLE DOMAIN SUCCESS:', { consumableId: args.id })
        return true
      } catch (error: any) {
        console.error('❌ DELETE_FULFILLMENT_CONSUMABLE DOMAIN ERROR:', error)
        throw new GraphQLError(`Ошибка при удалении расходника: ${error.message}`)
      }
    }),

    // =============================================================================
    // 🚚 МУТАЦИИ ДЛЯ ЛОГИСТИКИ ФУЛФИЛМЕНТА
    // =============================================================================

    // Создание логистического маршрута
    createFulfillmentLogistics: withAuth(async (
      _: unknown,
      args: { input: CreateFulfillmentLogisticsInput },
      context: Context,
    ) => {
      console.log('🔍 CREATE_FULFILLMENT_LOGISTICS DOMAIN MUTATION STARTED:', { userId: context.user?.id })
      try {
        const user = await checkFulfillmentAccess(context.user!.id)

        const logistics = await prisma.fulfillmentLogistics.create({
          data: {
            fulfillmentId: user.organizationId!,
            fromLocation: args.input.fromLocation,
            toLocation: args.input.toLocation,
            fromAddress: args.input.fromAddress,
            toAddress: args.input.toAddress,
            priceUnder1m3: args.input.priceUnder1m3,
            priceOver1m3: args.input.priceOver1m3,
            estimatedDays: args.input.estimatedDays,
            description: args.input.description,
            isActive: true,
            sortOrder: args.input.sortOrder || 0,
          },
          include: {
            fulfillment: true,
          },
        })

        const result = {
          success: true,
          message: 'Логистический маршрут успешно создан',
          logistics,
        }
        console.log('✅ CREATE_FULFILLMENT_LOGISTICS DOMAIN SUCCESS:', { logisticsId: logistics.id })
        return result
      } catch (error: any) {
        console.error('❌ CREATE_FULFILLMENT_LOGISTICS DOMAIN ERROR:', error)
        return {
          success: false,
          message: `Ошибка при создании логистического маршрута: ${error.message}`,
          logistics: null,
        }
      }
    }),

    // Обновление логистического маршрута
    updateFulfillmentLogistics: withAuth(async (
      _: unknown,
      args: { input: UpdateFulfillmentLogisticsInput },
      context: Context,
    ) => {
      console.log('🔍 UPDATE_FULFILLMENT_LOGISTICS DOMAIN MUTATION STARTED:', { 
        userId: context.user?.id,
        logisticsId: args.input.id,
      })
      try {
        const user = await checkFulfillmentAccess(context.user!.id)

        // Проверяем что маршрут принадлежит текущему фулфилменту
        const existingLogistics = await prisma.fulfillmentLogistics.findFirst({
          where: {
            id: args.input.id,
            fulfillmentId: user.organizationId!,
          },
        })

        if (!existingLogistics) {
          return {
            success: false,
            message: 'Логистический маршрут не найден или не принадлежит вашей организации',
            logistics: null,
          }
        }

        const updateData: any = {}
        if (args.input.fromLocation !== undefined) updateData.fromLocation = args.input.fromLocation
        if (args.input.toLocation !== undefined) updateData.toLocation = args.input.toLocation
        if (args.input.fromAddress !== undefined) updateData.fromAddress = args.input.fromAddress
        if (args.input.toAddress !== undefined) updateData.toAddress = args.input.toAddress
        if (args.input.priceUnder1m3 !== undefined) updateData.priceUnder1m3 = args.input.priceUnder1m3
        if (args.input.priceOver1m3 !== undefined) updateData.priceOver1m3 = args.input.priceOver1m3
        if (args.input.estimatedDays !== undefined) updateData.estimatedDays = args.input.estimatedDays
        if (args.input.description !== undefined) updateData.description = args.input.description
        if (args.input.sortOrder !== undefined) updateData.sortOrder = args.input.sortOrder
        if (args.input.isActive !== undefined) updateData.isActive = args.input.isActive

        const logistics = await prisma.fulfillmentLogistics.update({
          where: { id: args.input.id },
          data: updateData,
          include: {
            fulfillment: true,
          },
        })

        const result = {
          success: true,
          message: 'Логистический маршрут успешно обновлен',
          logistics,
        }
        console.log('✅ UPDATE_FULFILLMENT_LOGISTICS DOMAIN SUCCESS:', { logisticsId: logistics.id })
        return result
      } catch (error: any) {
        console.error('❌ UPDATE_FULFILLMENT_LOGISTICS DOMAIN ERROR:', error)
        return {
          success: false,
          message: `Ошибка при обновлении логистического маршрута: ${error.message}`,
          logistics: null,
        }
      }
    }),

    // Удаление логистического маршрута
    deleteFulfillmentLogistics: withAuth(async (_: unknown, args: { id: string }, context: Context) => {
      console.log('🔍 DELETE_FULFILLMENT_LOGISTICS DOMAIN MUTATION STARTED:', { 
        userId: context.user?.id,
        logisticsId: args.id,
      })
      try {
        const user = await checkFulfillmentAccess(context.user!.id)

        // Проверяем что маршрут принадлежит текущему фулфилменту
        const existingLogistics = await prisma.fulfillmentLogistics.findFirst({
          where: {
            id: args.id,
            fulfillmentId: user.organizationId!,
          },
        })

        if (!existingLogistics) {
          throw new GraphQLError('Логистический маршрут не найден или не принадлежит вашей организации')
        }

        await prisma.fulfillmentLogistics.delete({
          where: { id: args.id },
        })

        console.log('✅ DELETE_FULFILLMENT_LOGISTICS DOMAIN SUCCESS:', { logisticsId: args.id })
        return true
      } catch (error: any) {
        console.error('❌ DELETE_FULFILLMENT_LOGISTICS DOMAIN ERROR:', error)
        throw new GraphQLError(`Ошибка при удалении логистического маршрута: ${error.message}`)
      }
    }),

    // V1 Legacy: Обновить цену инвентаря фулфилмента
    updateFulfillmentInventoryPrice: withAuth(async (
      _: unknown,
      args: {
        inventoryId: string
        price: number
        priceType?: string
        notes?: string
      },
      context: Context,
    ) => {
      console.warn('💰 UPDATE_FULFILLMENT_INVENTORY_PRICE (V1) - LEGACY RESOLVER:', {
        inventoryId: args.inventoryId,
        price: args.price,
        priceType: args.priceType,
      })

      try {
        const user = await checkFulfillmentAccess(context.user!.id)

        // TODO: Реализовать V1 логику обновления цены инвентаря фулфилмента
        // Может потребоваться интеграция с V2 системой ценообразования услуг
        
        return {
          success: false,
          message: 'V1 Legacy - требуется реализация обновления цены инвентаря фулфилмента',
          inventory: null,
        }
      } catch (error: any) {
        console.error('❌ UPDATE_FULFILLMENT_INVENTORY_PRICE DOMAIN ERROR:', error)
        return {
          success: false,
          message: error.message || 'Ошибка при обновлении цены инвентаря',
          inventory: null,
        }
      }
    }),
  },
}

console.warn('🔥 SERVICES DOMAIN МОДУЛЬ ЭКСПОРТЫ ГОТОВЫ')