/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unused-vars */
import type { Transaction } from "../generated/kysely-tailordb";
import { PriceRuleNotFoundError } from "../lib/errors.generated";
import { selectOne } from "../lib/domain";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

export interface DeactivatePurchasePriceRuleInput {
  id: string;
}

export async function run(
  db: Transaction,
  input: DeactivatePurchasePriceRuleInput,
  ctx: CommandContext,
) {
  const purchasePriceRule = await selectOne(db, "PurchasePriceRule", "id", input.id, true);
  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 });
}
