/* 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 DeactivatePurchasePriceListInput {
  id: string;
}

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