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

export type GetLotInput = { id: string } | { lotNumber: string; itemId: string };

export async function run(db: ReadonlyDB<DB>, input: GetLotInput) {
  let query = db.selectFrom("Lot").selectAll();

  if ("id" in input) {
    query = query.where("id", "=", input.id);
  } else {
    query = query.where("lotNumber", "=", input.lotNumber).where("itemId", "=", input.itemId);
  }

  const lot = await query.executeTakeFirst();

  if (!lot) {
    return ok({ lot: null, lotStockLevels: [] });
  }

  const lotStockLevels = await db
    .selectFrom("LotStockLevel")
    .selectAll()
    .where("lotId", "=", lot.id)
    .execute();

  return ok({ lot, lotStockLevels });
}
