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

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 moveLines = await db
    .selectFrom("StockMoveLine")
    .innerJoin("StockMovement", "StockMovement.id", "StockMoveLine.stockMovementId")
    .selectAll("StockMoveLine")
    .select([
      "StockMovement.movementType",
      "StockMovement.executedAt",
      "StockMovement.status",
      "StockMovement.reasonCode",
    ])
    .where("StockMoveLine.lotId", "=", input.lotId)
    .where("StockMovement.movementType", "=", "GOODS_ISSUE")
    .orderBy("StockMoveLine.createdAt", "asc")
    .execute();

  return ok({ moveLines });
}
