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 ReactivateCostElementInput {
  costElementId: string;
  from?: string[];
}

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

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

  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: "ACTIVE", updatedAt: new Date() })
    .where("id", "=", input.costElementId)
    .returningAll()
    .executeTakeFirst();

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