import type { DB } from "../generated/kysely-tailordb";
import { ok, type ReadonlyDB } from "@tailor-platform/erp-kit/module";

export interface GetStockLevelInput {
  itemId: string;
  storageLocationId: string;
}

export async function run(db: ReadonlyDB<DB>, input: GetStockLevelInput) {
  const stockLevel = await db
    .selectFrom("StockLevel")
    .selectAll()
    .where("itemId", "=", input.itemId)
    .where("storageLocationId", "=", input.storageLocationId)
    .executeTakeFirst();

  if (!stockLevel) {
    return ok({ stockLevel: null });
  }

  const availableQuantity = stockLevel.onHand - stockLevel.reserved - stockLevel.blocked;

  return ok({ stockLevel: { ...stockLevel, availableQuantity } });
}
