// const { decrypt } = require("./encrytion");

// /**
//  * Decrypts specified fields in a single record.
//  * Handles multi-line encrypted values properly.
//  * @param {object} record - The record object to process.
//  * @param {string} key - The secret key for decryption.
//  * @param {Array<string>} fieldsToDecrypt - The list of fields to decrypt.
//  * @returns {object} The record with decrypted fields.
//  */
// const decryptRecord = (record, key, fieldsToDecrypt) => {
//   for (const field of fieldsToDecrypt) {
//     if (record[field]) {
//       try {
//         // Check if the field contains multiple encrypted values separated by \n
//         let encryptedParts = record[field].split("\n");

//         // Decrypt each part separately
//         let decryptedParts = encryptedParts.map((encryptedPart) =>
//           decrypt(encryptedPart, key)
//         );

//         // Join the decrypted parts with new lines
//         record[field] = decryptedParts.join("\n");
//       } catch (err) {
//         console.error(
//           `Failed to decrypt field '${field}' for record ID ${record.id}:`,
//           err.message
//         );
//         record[field] = null; // Handle decryption errors safely
//       }
//     }
//   }
//   return record;
// };

// /**
//  * Decrypts specified fields in a list of records.
//  * @param {Array<object>} records - The list of records to process.
//  * @param {string} key - The secret key for decryption.
//  * @param {Array<string>} fieldsToDecrypt - The list of fields to decrypt.
//  * @returns {Array<object>} The list with decrypted records.
//  */
// const decryptRecords = (records, key, fieldsToDecrypt) => {
//   return records.map((record) => decryptRecord(record, key, fieldsToDecrypt));
// };

// module.exports = { decryptRecord, decryptRecords };

const logger = require("../handlers/logger");
const { decrypt } = require("./encrytion");

/**
 * Decrypts specified fields in a single record.
 * Special handling for `rx` as encrypted JSON string.
 * @param {object} record - The record object to process.
 * @param {string} key - The secret key for decryption.
 * @param {Array<string>} fieldsToDecrypt - The list of fields to decrypt (excluding rx).
 * @returns {object} The record with decrypted fields.
 */
const decryptRecord = (record, key, fieldsToDecrypt) => {
  for (const field of Object.keys(record)) {
    try {
      if (field === "rx" && record[field]) {
        let decryptedRx;

        // Try NEW FORMAT: full RX is encrypted JSON string
        try {
          const decrypted = decrypt(record[field], key);
          decryptedRx = JSON.parse(decrypted);
        } catch (_) {
          // FALLBACK: Already a JSON array with encrypted fields
          try {
            const raw =
              typeof record[field] === "string"
                ? JSON.parse(record[field])
                : record[field];

            if (Array.isArray(raw)) {
              decryptedRx = raw.map((item) => ({
                drug_id:
                  item.drug_id == "N/A" || !item.drug_id
                    ? "N/A"
                    : decrypt(item.drug_id, key),
                drug_name: decrypt(item.drug_name, key),
                dosage: item.dosage ? decrypt(item.dosage, key) : "",
                quantity: item.quantity ?? 0,
                sp_pu: item.sp_pu ?? 0,
              }));
            } else {
              throw "Old rx format not an array.";
            }
          } catch (innerErr) {
            throw "Fallback RX parsing failed: " + innerErr.message;
          }
        }

        record[field] = decryptedRx;
        continue;
      }

      // Multi-line text fields
      if (fieldsToDecrypt.includes(field) && record[field]) {
        const encryptedParts = record[field].split("\n");
        const decryptedParts = encryptedParts.map((part) => decrypt(part, key));
        record[field] = decryptedParts.join("\n");
      }
    } catch (err) {
      logger.error(`Decryption failed for field '${field}':`, err.message);
      record[field] = null;
    }
  }

  return record;
};

/**
 * Decrypts specified fields in a list of records.
 * @param {Array<object>} records - The list of records to process.
 * @param {string} key - The secret key for decryption.
 * @param {Array<string>} fieldsToDecrypt - The list of fields to decrypt.
 * @returns {Array<object>} The list with decrypted records.
 */
const decryptRecords = (records, key, fieldsToDecrypt) => {
  return records.map((record) => decryptRecord(record, key, fieldsToDecrypt));
};

module.exports = { decryptRecord, decryptRecords };
