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

export interface DeactivateSalesPriceListInput {
  salesPriceListId: string;
}

export async function run(
  db: Transaction,
  input: DeactivateSalesPriceListInput,
  ctx: CommandContext,
) {
  void ctx;
  const salesPriceList = await db
    .selectFrom("SalesPriceList")
    .selectAll()
    .where("id", "=", input.salesPriceListId)
    .forUpdate()
    .executeTakeFirst();
  if (!salesPriceList) {
    return err(new SalespricelistNotFoundError(input.salesPriceListId));
  }
  if (salesPriceList.status !== "ACTIVE") {
    return err(new InvalidSalespricelistStatusError(input.salesPriceListId));
  }
  const updated = await db
    .updateTable("SalesPriceList")
    .set({ status: "INACTIVE", updatedAt: new Date() })
    .where("id", "=", input.salesPriceListId)
    .returningAll()
    .executeTakeFirst();
  return ok({ salesPriceList: updated! });
}
