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

export interface ReleaseAccountPayableDocumentHoldInput {
  id: string;
  releaseReason?: string | null;
}

export async function run(
  db: Transaction,
  input: ReleaseAccountPayableDocumentHoldInput,
  _ctx: CommandContext,
) {
  const hold = await db
    .selectFrom("AccountPayableDocumentHold")
    .selectAll()
    .where("id", "=", input.id)
    .forUpdate()
    .executeTakeFirst();
  if (!hold) return err(new ApHoldNotFoundError(input.id));
  if (hold.releasedAt !== null) return err(new ApHoldAlreadyReleasedError(input.id));

  const releasedHold = await db
    .updateTable("AccountPayableDocumentHold")
    .set({ releasedAt: new Date(), releaseReason: input.releaseReason ?? null })
    .where("id", "=", input.id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ accountPayableDocumentHold: releasedHold });
}
