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

export interface TraceLotForwardInput {
  lotId: string;
}

export async function run(db: ReadonlyDB<DB>, input: TraceLotForwardInput) {
  const lot = await db
    .selectFrom("Lot")
    .selectAll()
    .where("id", "=", input.lotId)
    .executeTakeFirst();

  if (!lot) {
    return err(new LotNotFoundError(input.lotId));
  }

  const entries = await db
    .selectFrom("InventoryLedger")
    .innerJoin(
      "InventoryExecution",
      "InventoryExecution.id",
      "InventoryLedger.inventoryExecutionId",
    )
    .selectAll("InventoryLedger")
    .where("InventoryLedger.lotId", "=", input.lotId)
    .where("InventoryExecution.executionType", "=", "GOODS_ISSUE")
    .orderBy("InventoryLedger.createdAt", "asc")
    .execute();

  return ok({ entries });
}
