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

export interface DeactivateSalesPriceRuleInput {
  salesPriceRuleId: string;
}

export async function run(
  db: Transaction,
  input: DeactivateSalesPriceRuleInput,
  ctx: CommandContext,
) {
  void ctx;
  const salesPriceRule = await db
    .selectFrom("SalesPriceRule")
    .selectAll()
    .where("id", "=", input.salesPriceRuleId)
    .forUpdate()
    .executeTakeFirst();
  if (!salesPriceRule) {
    return err(new SalespriceruleNotFoundError(input.salesPriceRuleId));
  }
  if (salesPriceRule.status !== "ACTIVE") {
    return err(new InvalidSalespriceruleStatusError(input.salesPriceRuleId));
  }
  const updated = await db
    .updateTable("SalesPriceRule")
    .set({ status: "INACTIVE", updatedAt: new Date() })
    .where("id", "=", input.salesPriceRuleId)
    .returningAll()
    .executeTakeFirst();
  return ok({ salesPriceRule: updated! });
}
