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

export interface GetInventoryCountInput {
  id: string;
}

export async function run(db: ReadonlyDB<DB>, input: GetInventoryCountInput) {
  const inventoryCount = await db
    .selectFrom("InventoryCount")
    .selectAll()
    .where("id", "=", input.id)
    .executeTakeFirst();

  if (!inventoryCount) {
    return err(new CountNotFoundError(input.id));
  }

  const countLines = await db
    .selectFrom("InventoryCountLine")
    .selectAll()
    .where("inventoryCountId", "=", inventoryCount.id)
    .execute();

  return ok({ inventoryCount, countLines });
}
