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

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));
  }
  const nextStatus = purchasePriceRuleLifecycle.tryTransition(
    purchasePriceRule.status,
    "deactivate",
  );
  if (!nextStatus) {
    return ok({ purchasePriceRule });
  }

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

  return ok({ purchasePriceRule: deactivated });
}
