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

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 = new Decimal(stockLevel.onHand)
    .minus(stockLevel.reserved)
    .minus(stockLevel.blocked)
    .toString();

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