import { prisma } from './prisma';

// Single entry point for every stock movement — purchases in (positive
// delta), sales out (negative delta), deletions undoing either. Counts are
// info-only and may go negative (the stock page highlights that as "your
// records are out of sync"); nothing here ever blocks a sale.
//
// `size` is normalised to '' for sizeless products (mugs, phone cases) so the
// (productId, color, size) unique index actually dedupes — SQLite treats
// NULLs in a unique index as all distinct.
export async function adjustStock(productId: string, color: string, size: string | null, delta: number) {
  if (delta === 0) return;
  const sizeKey = size ?? '';
  await prisma.stockLevel.upsert({
    where: { productId_color_size: { productId, color, size: sizeKey } },
    create: { productId, color, size: sizeKey, quantity: delta },
    update: { quantity: { increment: delta } },
  });
}

type StockMovableItem = {
  productId: string | null;
  color: string | null;
  size: string | null;
  quantity: number;
};

// Applies a batch of sale/purchase lines to stock. `direction` +1 for stock
// coming in (purchases), -1 for going out (sales). Lines without a productId
// (free-text sale items, material purchase lines) carry no stock and are
// skipped.
export async function applyStockMovement(items: StockMovableItem[], direction: 1 | -1) {
  for (const item of items) {
    if (!item.productId) continue;
    await adjustStock(item.productId, item.color ?? '', item.size, direction * item.quantity);
  }
}
