import { inventoryItem, stockReservation } from '@platform-modules/commerce-inventory';
import type { DrizzleDb } from '@/server/db/client.js';
import { toModuleRef, asSkuId, asVendorId } from '@/server/platform-seams/ids.js';

export async function seedInventoryItems(
  db: DrizzleDb,
  rows: Array<{ id: string; vendorId: string; quantityTotal: number; quantitySold: number }>,
): Promise<number> {
  const inserted = await db
    .insert(inventoryItem)
    .values(
      rows.map((row) => ({
        skuId: toModuleRef(asSkuId(row.id)),
        vendorId: toModuleRef(asVendorId(row.vendorId)),
        quantityTotal: row.quantityTotal,
        quantitySold: row.quantitySold,
      })),
    )
    .onConflictDoNothing({ target: inventoryItem.skuId })
    .returning({ skuId: inventoryItem.skuId });
  return inserted.length;
}

export async function seedActiveReservations(
  db: DrizzleDb,
  rows: Array<{ id: string; skuId: string; qty: number; paymentIntentId: string; expiresAt: Date }>,
): Promise<number> {
  const inserted = await db
    .insert(stockReservation)
    .values(
      rows.map((row) => ({
        id: row.id,
        skuId: toModuleRef(asSkuId(row.skuId)),
        qty: row.qty,
        holderRef: row.paymentIntentId,
        expiresAt: row.expiresAt,
      })),
    )
    .onConflictDoNothing({ target: stockReservation.id })
    .returning({ id: stockReservation.id });
  return inserted.length;
}
