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

export interface GetGoodsIssueInput {
  id: string;
}

export async function run(db: ReadonlyDB<DB>, input: GetGoodsIssueInput) {
  const inventoryExecution = await db
    .selectFrom("InventoryExecution")
    .selectAll()
    .where("id", "=", input.id)
    .where("executionType", "=", "GOODS_ISSUE")
    .executeTakeFirst();

  if (!inventoryExecution) {
    return ok({ inventoryExecution: null, inventoryExecutionLines: [] });
  }

  const inventoryExecutionLines = await db
    .selectFrom("InventoryExecutionLine")
    .selectAll()
    .where("inventoryExecutionId", "=", input.id)
    .execute();

  return ok({ inventoryExecution, inventoryExecutionLines });
}
