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

export interface ApprovePurchaseChangeOrderInput {
  id: string;
}

export async function run(
  db: Transaction,
  input: ApprovePurchaseChangeOrderInput,
  ctx: CommandContext,
) {
  void ctx;
  const changeOrder = await db
    .selectFrom("PurchaseChangeOrder")
    .selectAll()
    .where("id", "=", input.id)
    .forUpdate()
    .executeTakeFirst();
  if (!changeOrder) {
    return err(new CoNotFoundError(input.id));
  }
  if (changeOrder.changeOrderStatus !== "SUBMITTED") {
    return err(new CoNotSubmittedError(input.id));
  }

  const approved = await db
    .updateTable("PurchaseChangeOrder")
    .set({ changeOrderStatus: "APPROVED", updatedAt: new Date() })
    .where("id", "=", input.id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ changeOrder: approved });
}
