"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var encryption_service_exports = {};
__export(encryption_service_exports, {
  default: () => encryption_service_default,
  encryptionService: () => encryptionService
});
module.exports = __toCommonJS(encryption_service_exports);
var import_crypto = __toESM(require("crypto"));
class EncryptionService {
  // 128 bits
  constructor() {
    this.algorithm = "aes-256-gcm";
    this.keyLength = 32;
    // 256 bits
    this.ivLength = 12;
    // 96 bits for GCM
    this.tagLength = 16;
    const key = process.env.ENCRYPTION_KEY;
    if (!key) {
      throw new Error("ENCRYPTION_KEY environment variable is not set");
    }
    if (key.length < this.keyLength) {
      throw new Error(
        `ENCRYPTION_KEY must be at least ${this.keyLength} characters long`
      );
    }
    this.secretKey = Buffer.from(key.substring(0, this.keyLength), "utf-8");
  }
  encryptData(plainText) {
    try {
      if (!plainText) {
        throw new Error("Plain text cannot be empty");
      }
      const iv = import_crypto.default.randomBytes(this.ivLength);
      const cipher = import_crypto.default.createCipheriv(
        this.algorithm,
        this.secretKey,
        iv
      );
      let encrypted = cipher.update(plainText, "utf-8", "hex");
      encrypted += cipher.final("hex");
      const tag = cipher.getAuthTag();
      return `${iv.toString("base64")}:${encrypted}:${tag.toString("base64")}`;
    } catch (error) {
      throw new Error(
        `Encryption failed: ${error instanceof Error ? error.message : "Unknown error"}`
      );
    }
  }
  decryptData(encryptedPayload) {
    try {
      const [ivB64, encryptedHex, tagB64] = encryptedPayload.split(":");
      const iv = Buffer.from(ivB64, "base64");
      const tag = Buffer.from(tagB64, "base64");
      const encryptedBuffer = Buffer.from(encryptedHex, "hex");
      if (iv.length !== this.ivLength) {
        throw new Error(
          `Invalid IV length. Expected ${this.ivLength}, got ${iv.length}`
        );
      }
      const decipher = import_crypto.default.createDecipheriv(
        this.algorithm,
        this.secretKey,
        iv
      );
      decipher.setAuthTag(tag);
      let decrypted = decipher.update(
        encryptedBuffer,
        void 0,
        "utf-8"
      );
      decrypted += decipher.final("utf-8");
      return decrypted;
    } catch (error) {
      throw new Error(
        `Decryption failed: ${error instanceof Error ? error.message : "Unknown error"}`
      );
    }
  }
  // Helper method to convert any value to string for encryption
  valueToString(value) {
    if (value === null || value === void 0) {
      return "";
    }
    if (typeof value === "string") {
      return value;
    }
    if (typeof value === "boolean") {
      return value ? "true" : "false";
    }
    if (typeof value === "number") {
      return value.toString();
    }
    return JSON.stringify(value);
  }
  async encryptTableData(tableData) {
    return tableData.map((item) => {
      try {
        const stringValue = this.valueToString(item.config_value);
        if (!stringValue) {
          return item;
        }
        const encrypted = encryptionService.encryptData(stringValue);
        item.config_value = encrypted;
        return item;
      } catch (error) {
        throw new Error(
          `Failed to encrypt item: ${error instanceof Error ? error.message : "Unknown error"}`
        );
      }
    });
  }
  async decryptResultData(data) {
    try {
      const decryptedData = { ...data };
      for (const key in decryptedData) {
        if (decryptedData.hasOwnProperty(key)) {
          const value = decryptedData[key];
          if (value) {
            try {
              decryptedData[key] = await this.decryptData(value);
            } catch (error) {
              console.error(`Error decrypting ${key}: ${error.message}`);
              decryptedData[key] = null;
            }
          }
        }
      }
      return decryptedData;
    } catch (error) {
      throw new Error(`Decryption failed for the data: ${error.message}`);
    }
  }
  /*
   
   
   
  ## when no data found in the config_value enable this funcation ##
   
  private isJsonString(str: any): boolean {
    if (typeof str !== "string") return false;
    try {
      JSON.parse(str);
      return true;
    } catch {
      return false;
    }
  }
   
    public async decryptResultData(data: any): Promise<any> {
      try {
        const decryptedData: any = { ...data };
   
        for (const key in decryptedData) {
          if (!decryptedData.hasOwnProperty(key)) continue;
   
          const rawValue = decryptedData[key];
   
          let value = rawValue;
   
          // Parse only JSON strings
          if (this.isJsonString(rawValue)) {
            value = JSON.parse(rawValue);
          }
   
          // Decrypt only if value looks encrypted (your own rule)
          if (value && typeof value === 'string' && value.startsWith('enc:')) {
            try {
              decryptedData[key] = await this.decryptData(value);
            } catch (error: any) {
              console.error(`Error decrypting ${key}: ${error.message}`);
              decryptedData[key] = null;
            }
          } else {
            // Not encrypted → keep as original value
            decryptedData[key] = rawValue;
          }
        }
   
        return decryptedData;
      } catch (error: any) {
        throw new Error(`Decryption failed for the data: ${error.message}`);
      }
    }
    */
  async decryptTableData(tableData) {
    return tableData.map((item) => {
      try {
        console.log(item.config_value);
        if (!item.config_value) {
          return item;
        }
        const encryptedData = item.config_value;
        item.config_value = encryptionService.decryptData(encryptedData);
        return item;
      } catch (error) {
        throw new Error(
          `Failed to decrypt item: ${error instanceof Error ? error.message : "Unknown error"}`
        );
      }
    });
  }
}
const encryptionService = new EncryptionService();
var encryption_service_default = EncryptionService;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  encryptionService
});
