import { getPublicKeyAsync, signAsync } from "@noble/ed25519";
import { base64UrlToBytes, bytesToBase64Url, textToBytes } from "./encoding";
import type { StoredKeys } from "./types";

function randomPrivateKey(): Uint8Array {
  const out = new Uint8Array(32);
  crypto.getRandomValues(out);
  return out;
}

export async function generateKeyPair(): Promise<StoredKeys> {
  const privateKey = randomPrivateKey();
  const publicKey = await getPublicKeyAsync(privateKey);
  return {
    publicKey: bytesToBase64Url(publicKey),
    privateKey: bytesToBase64Url(privateKey),
  };
}

export async function getPublicKeyFromPrivate(privateKeyBase64: string): Promise<string> {
  const privateKey = base64UrlToBytes(privateKeyBase64);
  const publicKey = await getPublicKeyAsync(privateKey);
  return bytesToBase64Url(publicKey);
}

export async function signMessage(privateKeyBase64: string, message: string): Promise<string> {
  const privateKey = base64UrlToBytes(privateKeyBase64);
  const signature = await signAsync(textToBytes(message), privateKey);
  return bytesToBase64Url(signature);
}
