const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const { machineIdSync } = require("node-machine-id");

const LICENSE_FILE_PATH = path.join(__dirname, "../license.enc"); // Encrypted file path
const SECRET_KEY = process.env.enc_key;
const ALGORITHM = "aes-256-cbc";
const IV = Buffer.alloc(16, 0); // Fixed IV for encryption

// Encrypt data
function encryptData(data) {
  const cipher = crypto.createCipheriv(
    ALGORITHM,
    Buffer.from(SECRET_KEY, "utf-8"),
    IV
  );
  let encrypted = cipher.update(JSON.stringify(data), "utf-8", "hex");
  encrypted += cipher.final("hex");
  return encrypted;
}

// Decrypt data
function decryptData(encryptedData) {
  try {
    const decipher = crypto.createDecipheriv(
      ALGORITHM,
      Buffer.from(SECRET_KEY, "utf-8"),
      IV
    );
    let decrypted = decipher.update(encryptedData, "hex", "utf-8");
    decrypted += decipher.final("utf-8");
    return JSON.parse(decrypted);
  } catch (error) {
    return null;
  }
}

// Save license with machine ID
function saveLicense(licenseData) {
  licenseData.machine_id = machineIdSync(); // Store current machine ID
  const encryptedData = encryptData(licenseData);
  fs.writeFileSync(LICENSE_FILE_PATH, encryptedData, "utf-8");
}

// Load and decrypt license
function loadLicense() {
  if (!fs.existsSync(LICENSE_FILE_PATH)) return null;
  const encryptedData = fs.readFileSync(LICENSE_FILE_PATH, "utf-8");
  return decryptData(encryptedData);
}

// Check if machine ID matches
function verifyMachine() {
  const licenseData = loadLicense();
  if (!licenseData)
    return { success: false, message: "License file missing or corrupted." };

  const currentMachineId = machineIdSync();
  if (licenseData.machine_id !== currentMachineId) {
    return {
      success: false,
      message: "Unrecognized machine, contact support.",
    };
  }

  return { success: true };
}

module.exports = { saveLicense, loadLicense, verifyMachine };
