/**
 * VAPID Key Generator
 *
 * Run once with: npx tsx scripts/generate-vapid.ts
 *
 * Outputs the VAPID_PUBLIC_KEY and VAPID_PRIVATE_KEY values to add to .env.local
 *
 * Uses Node.js built-in crypto (no npm packages needed).
 * Keys are P-256 / prime256v1 as required by the Web Push Protocol (RFC 8030 / 8291).
 */
import crypto from "node:crypto";

function toBase64url(buf: Buffer): string {
  return buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}

const { publicKey, privateKey } = crypto.generateKeyPairSync("ec", {
  namedCurve: "prime256v1",
  publicKeyEncoding: { type: "spki", format: "der" },
  privateKeyEncoding: { type: "pkcs8", format: "der" },
});

// The raw 65-byte uncompressed EC public key lives at bytes [27..92] of the SPKI DER.
// (18-byte SPKI header + 1 byte BIT-STRING unused bits marker = 27 bytes of prefix)
const rawPublic = publicKey.subarray(27);
// The raw 32-byte EC private key lives at bytes [36..68] of the PKCS#8 DER.
// PKCS#8 header is 36 bytes for prime256v1.
const rawPrivate = privateKey.subarray(36, 68);

console.log("\n\n==== VAPID Key Generation Complete ====\n");
console.log("Add these to your .env.local:\n");
console.log(`VAPID_PUBLIC_KEY=${toBase64url(rawPublic)}`);
console.log(`VAPID_PRIVATE_KEY=${toBase64url(rawPrivate)}`);
console.log(`VAPID_SUBJECT=mailto:admin@qutoai.com`);
console.log("\n=======================================\n");
