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 ActivatePurchasePriceListInput {
  id: string;
}

export async function run(
  db: Transaction,
  input: ActivatePurchasePriceListInput,
  _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 === "ACTIVE") {
    return ok({ purchasePriceList });
  }

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

  return ok({ purchasePriceList: activated });
}
