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

export interface GetSerialNumberHistoryInput {
  serialNumberId: string;
}

export async function run(db: ReadonlyDB<DB>, input: GetSerialNumberHistoryInput) {
  const serialNumber = await db
    .selectFrom("SerialNumber")
    .selectAll()
    .where("id", "=", input.serialNumberId)
    .executeTakeFirst();

  if (!serialNumber) {
    return err(new SerialNumberNotFoundError(input.serialNumberId));
  }

  const entries = await db
    .selectFrom("InventoryLedger")
    .selectAll()
    .where("serialNumberId", "=", input.serialNumberId)
    .orderBy("executedAt", "asc")
    .execute();

  return ok({ entries });
}
