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

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

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

  return ok({ purchasePriceList: deactivated });
}
