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

export interface ReviseInventoryAdjustmentInput {
  id: string;
}

/**
 * Function: reviseInventoryAdjustment
 *
 * Transitions a rejected inventory adjustment back to DRAFT status,
 * allowing the user to modify and resubmit it.
 */
export async function run(
  db: Transaction,
  input: ReviseInventoryAdjustmentInput,
  _ctx: CommandContext,
) {
  const { id } = input;

  // 1. Fetch adjustment
  const adjustment = await db
    .selectFrom("InventoryAdjustment")
    .selectAll()
    .where("id", "=", id)
    .forUpdate()
    .executeTakeFirst();

  if (!adjustment) {
    return err(new AdjustmentNotFoundError(id));
  }

  // 2. Validate status is REJECTED
  if (adjustment.status !== "REJECTED") {
    return err(new AdjustmentNotRejectedError(id));
  }

  // 3. Update status to DRAFT
  const updated = await db
    .updateTable("InventoryAdjustment")
    .set({ status: "DRAFT", updatedAt: new Date() })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirst();

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