import type { Transaction } from "../generated/kysely-tailordb";
import { GoodsReceiptNotDraftError, GoodsReceiptNotFoundError } from "../lib/errors.generated";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";

export interface CancelGoodsReceiptInput {
  id: string;
}

export async function run(db: Transaction, input: CancelGoodsReceiptInput, ctx: CommandContext) {
  void ctx;
  const goodsReceipt = await db
    .selectFrom("GoodsReceipt")
    .selectAll()
    .where("id", "=", input.id)
    .forUpdate()
    .executeTakeFirst();
  if (!goodsReceipt) {
    return err(new GoodsReceiptNotFoundError(input.id));
  }
  if (goodsReceipt.status !== "DRAFT") {
    return err(new GoodsReceiptNotDraftError(input.id));
  }

  const cancelled = await db
    .updateTable("GoodsReceipt")
    .set({ status: "CANCELLED", updatedAt: new Date() })
    .where("id", "=", input.id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ goodsReceipt: cancelled });
}
