/**
 * License Key 生成器 — 内部工具
 *
 * 使用方式：
 *   node lib/license-generator.js --tier team --expires 2027-05-19 --licensee "Acme Corp" [--binding "acme.com"]
 *   或
 *   AINEOS_LICENSE_SECRET=<secret> node lib/license-generator.js ...
 */

const crypto = require("crypto");
const { encodeLicenseKey } = require("./license-crypto");

const TIER_MAP = { free: 0, team: 1, enterprise: 2 };

function generateLicenseKey({ tier, expiresAt, licensee, binding }) {
  const t = TIER_MAP[tier];
  if (t === undefined) throw new Error(`Invalid tier: ${tier}. Must be free, team, or enterprise.`);

  const licenseeHash = crypto.createHash("sha256").update(licensee || "unknown").digest("hex").slice(0, 8);

  const payload = {
    v: 1,
    t,
    e: new Date(expiresAt).getTime(),
    l: licenseeHash,
    b: binding || "",
  };

  return encodeLicenseKey(payload);
}

function generateBatchLicenses(list) {
  return list.map((opts) => ({
    licensee: opts.licensee,
    key: generateLicenseKey(opts),
    tier: opts.tier,
    expiresAt: opts.expiresAt,
  }));
}

// CLI 直接调用
if (require.main === module) {
  const args = process.argv.slice(2);
  const opts = { tier: "team", expiresAt: "", licensee: "", binding: "" };

  for (let i = 0; i < args.length; i++) {
    switch (args[i]) {
      case "--tier": opts.tier = args[++i]; break;
      case "--expires": opts.expiresAt = args[++i]; break;
      case "--licensee": opts.licensee = args[++i]; break;
      case "--binding": opts.binding = args[++i]; break;
      case "--batch": {
        const count = parseInt(args[++i], 10);
        const list = Array.from({ length: count }, (_, idx) => ({
          tier: opts.tier,
          expiresAt: opts.expiresAt,
          licensee: `${opts.licensee}-${idx + 1}`,
          binding: opts.binding,
        }));
        console.log(JSON.stringify(generateBatchLicenses(list), null, 2));
        process.exit(0);
      }
    }
  }

  if (!opts.expiresAt || !opts.licensee) {
    console.error("用法: node lib/license-generator.js --tier <team|enterprise> --expires <YYYY-MM-DD> --licensee <name> [--binding <domain>]");
    console.error("      node lib/license-generator.js --batch <count> --tier team --expires <YYYY-MM-DD> --licensee <base-name>");
    process.exit(1);
  }

  const key = generateLicenseKey(opts);
  console.log(key);
  console.error(`\n等级: ${opts.tier}  |  被授权方: ${opts.licensee}  |  到期: ${opts.expiresAt}`);
  if (opts.binding) console.error(`绑定: ${opts.binding}`);
}

module.exports = { generateLicenseKey, generateBatchLicenses };
