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

export interface CancelPurchaseBillInput {
  id: string;
}

export async function run(db: Transaction, input: CancelPurchaseBillInput, ctx: CommandContext) {
  void ctx;
  const purchaseBill = await db
    .selectFrom("PurchaseBill")
    .selectAll()
    .where("id", "=", input.id)
    .forUpdate()
    .executeTakeFirst();
  if (!purchaseBill) {
    return err(new PurchaseBillNotFoundError(input.id));
  }
  if (!["DRAFT", "BLOCKED"].includes(purchaseBill.status)) {
    return err(new PurchaseBillNotCancellableError(input.id));
  }

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

  return ok({ purchaseBill: cancelled });
}
