/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access */
import type { Transaction } from "../generated/kysely-tailordb";
import { GoodsReceiptNotDraftError, GoodsReceiptNotFoundError } from "../lib/errors.generated";
import { selectOne } from "../lib/domain";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

export interface CancelGoodsReceiptInput {
  id: string;
}

export async function run(db: Transaction, input: CancelGoodsReceiptInput, ctx: CommandContext) {
  void ctx;
  const goodsReceipt = await selectOne(db, "GoodsReceipt", "id", input.id, true);
  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 });
}
