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

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

  const encoder = new TextEncoder();
  const data = encoder.encode(text);

  const hashBuffer = await crypto.subtle.digest(options.algorithm, data);

  let outputStr = "";
  if (options.output === "hex") {
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    outputStr = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
  } else if (options.output === "base64") {
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    const binStr = String.fromCharCode(...hashArray);
    outputStr = btoa(binStr);
  }

  return {
    type: "text",
    value: outputStr,
  };
}
