import { createECDH, createPrivateKey, sign } from "node:crypto";
import { readFileSync } from "node:fs";

// A signer key file with hex keys, the format the console's
// Users page downloads.
const { signer_private_key } = JSON.parse(
  readFileSync(process.env.SIGNER_KEY_FILE!, "utf8"),
);
const ecdh = createECDH("prime256v1");
ecdh.setPrivateKey(Buffer.from(signer_private_key, "hex"));
const point = ecdh.getPublicKey(); // 0x04 || x || y
const key = createPrivateKey({
  format: "jwk",
  key: {
    kty: "EC",
    crv: "P-256",
    d: Buffer.from(signer_private_key, "hex").toString(
      "base64url",
    ),
    x: point.subarray(1, 33).toString("base64url"),
    y: point.subarray(33).toString("base64url"),
  },
});
const publicKey = ecdh.getPublicKey("hex", "compressed");

export function stamp(payload: string): string {
  const signature = sign(
    "sha256",
    Buffer.from(payload),
    key,
  ).toString("hex");
  const json = JSON.stringify({
    publicKey,
    signature,
    scheme: "SIGNATURE_SCHEME_TK_API_P256",
  });
  return Buffer.from(json).toString("base64url");
}
