import type { ToolInput } from "../../core/io/input-types";
import type { ToolResult } from "../../core/io/output-types";
import type { ToolContext } from "../../core/plugins/plugin-types";
import type { Base64Options } from "./index";

export async function runBase64(
  input: ToolInput,
  options: Base64Options,
  context: ToolContext
): Promise<ToolResult> {
  const text = input.text ?? "";

  if (!text) {
    return {
      type: "text",
      value: "",
    };
  }

  context.reportProgress({ percentage: 50, message: "Processing..." });

  try {
    const resultValue =
      options.mode === "encode"
        ? btoa(unescape(encodeURIComponent(text)))
        : decodeURIComponent(escape(atob(text)));

    context.reportProgress({ percentage: 100, message: "Done" });

    return {
      type: "text",
      value: resultValue,
    };
  } catch (cause) {
    throw new Error("Invalid Base64 input string or encoding error.", { cause });
  }
}
