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

export interface GetStockAdjustmentInput {
  id: string;
}

export async function run(db: ReadonlyDB<DB>, input: GetStockAdjustmentInput) {
  const stockAdjustment = await db
    .selectFrom("StockAdjustment")
    .selectAll()
    .where("id", "=", input.id)
    .executeTakeFirst();

  if (!stockAdjustment) {
    return ok({ stockAdjustment: null, stockAdjustmentLines: [] });
  }

  const stockAdjustmentLines = await db
    .selectFrom("StockAdjustmentLine")
    .selectAll()
    .where("stockAdjustmentId", "=", input.id)
    .execute();

  return ok({ stockAdjustment, stockAdjustmentLines });
}
