// =============================================================================
// 📦 INVENTORY MANAGEMENT ДЛЯ ТОВАРОВ СЕЛЛЕРА V2
// =============================================================================

import { Prisma } from '@prisma/client'

import { prisma } from '@/lib/prisma'

// =============================================================================
// 🔄 ПРИЕМКА ТОВАРОВ НА СКЛАД ФУЛФИЛМЕНТА
// =============================================================================

export async function processSellerGoodsSupplyReceipt(
  supplyOrderId: string,
): Promise<void> {
  console.log(`📦 Processing seller goods supply receipt: ${supplyOrderId}`)

  const supplyOrder = await prisma.sellerGoodsSupplyOrder.findUnique({
    where: { id: supplyOrderId },
    include: {
      seller: true,
      fulfillmentCenter: true,
      recipeItems: {
        include: {
          product: true,
        },
      },
    },
  })

  if (!supplyOrder) {
    throw new Error(`Seller goods supply order not found: ${supplyOrderId}`)
  }

  // Обрабатываем только товары типа MAIN_PRODUCT
  const mainProducts = supplyOrder.recipeItems.filter(
    item => item.recipeType === 'MAIN_PRODUCT',
  )

  for (const item of mainProducts) {
    // Находим или создаем запись инвентаря
    const existingInventory = await prisma.sellerGoodsInventory.findUnique({
      where: {
        sellerId_fulfillmentCenterId_productId: {
          sellerId: supplyOrder.sellerId,
          fulfillmentCenterId: supplyOrder.fulfillmentCenterId,
          productId: item.productId,
        },
      },
    })

    if (existingInventory) {
      // Обновляем существующий инвентарь
      const newAverageCost = calculateWeightedAverageCost(
        existingInventory.currentStock,
        existingInventory.averageCost.toNumber(),
        item.quantity,
        item.product.price.toNumber(),
      )

      await prisma.sellerGoodsInventory.update({
        where: { id: existingInventory.id },
        data: {
          currentStock: {
            increment: item.quantity,
          },
          totalReceived: {
            increment: item.quantity,
          },
          averageCost: newAverageCost,
          lastSupplyDate: new Date(),
        },
      })

      console.log(
        `✅ Updated inventory for ${item.product.name}: +${item.quantity} units`,
      )
    } else {
      // Создаем новую запись инвентаря
      await prisma.sellerGoodsInventory.create({
        data: {
          sellerId: supplyOrder.sellerId,
          fulfillmentCenterId: supplyOrder.fulfillmentCenterId,
          productId: item.productId,
          currentStock: item.quantity,
          totalReceived: item.quantity,
          averageCost: item.product.price,
          salePrice: item.product.price, // Можно будет настроить отдельно
          lastSupplyDate: new Date(),
        },
      })

      console.log(
        `✅ Created new inventory for ${item.product.name}: ${item.quantity} units`,
      )
    }

    // Снимаем резерв у поставщика
    await prisma.product.update({
      where: { id: item.productId },
      data: {
        ordered: {
          decrement: item.quantity,
        },
      },
    })
  }

  console.log('✅ Supply receipt processed successfully')
}

// =============================================================================
// 🧮 РАСЧЕТ СРЕДНЕВЗВЕШЕННОЙ СТОИМОСТИ
// =============================================================================

function calculateWeightedAverageCost(
  currentStock: number,
  currentCost: number,
  newQuantity: number,
  newCost: number,
): Prisma.Decimal {
  const totalValue = currentStock * currentCost + newQuantity * newCost
  const totalQuantity = currentStock + newQuantity
  const averageCost = totalQuantity > 0 ? totalValue / totalQuantity : 0
  
  return new Prisma.Decimal(averageCost.toFixed(2))
}

// =============================================================================
// 📤 ИСПОЛЬЗОВАНИЕ ТОВАРОВ (заготовка для будущего)
// =============================================================================

export async function useSellerGoodsFromInventory(
  sellerId: string,
  fulfillmentCenterId: string,
  productId: string,
  quantity: number,
  purpose: 'MARKETPLACE_SHIPMENT' | 'INTERNAL_USE' | 'DAMAGE',
): Promise<void> {
  console.log(
    `📤 Using ${quantity} units of product ${productId} for ${purpose}`,
  )

  const inventory = await prisma.sellerGoodsInventory.findUnique({
    where: {
      sellerId_fulfillmentCenterId_productId: {
        sellerId,
        fulfillmentCenterId,
        productId,
      },
    },
  })

  if (!inventory) {
    throw new Error('Inventory record not found')
  }

  if (inventory.currentStock < quantity) {
    throw new Error(
      `Insufficient stock. Available: ${inventory.currentStock}, requested: ${quantity}`,
    )
  }

  // Обновляем инвентарь
  await prisma.sellerGoodsInventory.update({
    where: { id: inventory.id },
    data: {
      currentStock: {
        decrement: quantity,
      },
      totalShipped: {
        increment: purpose === 'MARKETPLACE_SHIPMENT' ? quantity : 0,
      },
      lastShipDate: purpose === 'MARKETPLACE_SHIPMENT' ? new Date() : undefined,
    },
  })

  // TODO: Создать запись в таблице движений товаров (InventoryMovement)
  console.log(`✅ Inventory updated: -${quantity} units`)
}

// =============================================================================
// 🔄 РЕЗЕРВИРОВАНИЕ ТОВАРОВ (заготовка для будущего)
// =============================================================================

export async function reserveSellerGoods(
  sellerId: string,
  fulfillmentCenterId: string,
  productId: string,
  quantity: number,
): Promise<void> {
  const inventory = await prisma.sellerGoodsInventory.findUnique({
    where: {
      sellerId_fulfillmentCenterId_productId: {
        sellerId,
        fulfillmentCenterId,
        productId,
      },
    },
  })

  if (!inventory) {
    throw new Error('Inventory record not found')
  }

  const availableStock = inventory.currentStock - inventory.reservedStock
  if (availableStock < quantity) {
    throw new Error(
      `Insufficient available stock. Available: ${availableStock}, requested: ${quantity}`,
    )
  }

  await prisma.sellerGoodsInventory.update({
    where: { id: inventory.id },
    data: {
      reservedStock: {
        increment: quantity,
      },
    },
  })
}

// =============================================================================
// 🏭 ПЕРЕВОД В ПОДГОТОВКУ (заготовка для будущего)
// =============================================================================

export async function moveToPreparation(
  sellerId: string,
  fulfillmentCenterId: string,
  productId: string,
  quantity: number,
): Promise<void> {
  await prisma.sellerGoodsInventory.update({
    where: {
      sellerId_fulfillmentCenterId_productId: {
        sellerId,
        fulfillmentCenterId,
        productId,
      },
    },
    data: {
      reservedStock: {
        decrement: quantity,
      },
      inPreparationStock: {
        increment: quantity,
      },
    },
  })
}