import type { ToolInput } from "../../core/io/input-types";
import type { ToolResult } from "../../core/io/output-types";
import type { UrlEncoderOptions } from "./index";

export async function runUrlEncoder(
  input: ToolInput,
  options: UrlEncoderOptions
): Promise<ToolResult> {
  const text = input.text || "";
  if (!text) {
    throw new Error("No text provided.");
  }

  try {
    const outputStr =
      options.mode === "encode"
        ? options.component === "full" ? encodeURI(text) : encodeURIComponent(text)
        : options.component === "full" ? decodeURI(text) : decodeURIComponent(text);

    return {
      type: "text",
      value: outputStr,
    };
  } catch (cause) {
    const message = cause instanceof Error ? cause.message : String(cause);
    throw new Error(`Failed to process URL: ${message}`, { cause });
  }
}
