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

export interface DeactivatePurchasePriceRuleInput {
  id: string;
}

export async function run(
  db: Transaction,
  input: DeactivatePurchasePriceRuleInput,
  _ctx: CommandContext,
) {
  const purchasePriceRule = await db
    .selectFrom("PurchasePriceRule")
    .selectAll()
    .where("id", "=", input.id)
    .forUpdate()
    .executeTakeFirst();
  if (!purchasePriceRule) {
    return err(new PriceRuleNotFoundError(input.id));
  }
  if (purchasePriceRule.status === "INACTIVE") {
    return ok({ purchasePriceRule });
  }

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

  return ok({ purchasePriceRule: deactivated });
}
