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

export interface DeactivateCostElementInput {
  costElementId: string;
  from?: string[];
}

/** Command: deactivateCostElement
 * Transitions a cost element from ACTIVE status to INACTIVE status.
 */
export async function run(db: Transaction, input: DeactivateCostElementInput, ctx: CommandContext) {
  void ctx;

  const validFromStatuses = input.from ?? ["ACTIVE"];

  const costElement = await db
    .selectFrom("CostElement")
    .selectAll()
    .where("id", "=", input.costElementId)
    .forUpdate()
    .executeTakeFirst();

  if (!costElement) {
    return err(new CostElementNotFoundError(input.costElementId));
  }

  if (!validFromStatuses.includes(costElement.status)) {
    return err(new InvalidStateError(input.costElementId));
  }

  const updated = await db
    .updateTable("CostElement")
    .set({ status: "INACTIVE", updatedAt: new Date() })
    .where("id", "=", input.costElementId)
    .returningAll()
    .executeTakeFirst();

  return ok({ costElement: updated! });
}
