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

export interface DeactivatePurchasePriceListInput {
  id: string;
}

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

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

  return ok({ purchasePriceList: deactivated });
}
