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

export type GetSerialNumberInput = { id: string } | { serialNumber: string; itemId: string };

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

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

  const serialNumber = await query.executeTakeFirst();

  return ok({ serialNumber: serialNumber ?? null });
}
