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")
    .innerJoin(
      "InventoryExecution",
      "InventoryExecution.id",
      "InventoryLedger.inventoryExecutionId",
    )
    .selectAll("InventoryLedger")
    .select([
      "InventoryExecution.executionType as executionType",
      "InventoryExecution.sourceDocumentType as sourceDocumentType",
      "InventoryExecution.sourceDocumentId as sourceDocumentId",
    ])
    .where("InventoryLedger.serialNumberId", "=", input.serialNumberId)
    .orderBy("InventoryLedger.executedAt", "asc")
    .execute();

  return ok({ entries });
}
