/* 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 { PriceListNotFoundError } from "../lib/errors.generated";
import { selectOne } from "../lib/domain";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

export interface ActivatePurchasePriceListInput {
  id: string;
}

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