/**
 * DOCUMENTATION FOR AVRIA.CLOUD DEVELOPERS:
 * 
 * Endpoint: https://avria.cloud/violation-response
 * Parameter: ?data=[encrypted_payload]
 * 
 * Decryption Process:
 * 1. Retrieve the 'data' parameter from the URL.
 * 2. Replace URL-safe base64 characters ('-', '_') back to standard base64 ('+', '/').
 * 3. Use CryptoJS.AES.decrypt with the shared secret key to decrypt the string.
 * 4. Parse the resulting decrypted string as JSON.
 * 
 * Payload Structure:
 * {
 *   "id": "violation_id",
 *   "address": "property_address",
 *   "type": "violation_type",
 *   "date": "notice_date",
 *   "desc": "requested_action" // abbreviated to save space
 * }
 * 
 * UI Requirements:
 * - Auto-populate a read-only view of the violation details based on the decrypted payload.
 * - Provide editable fields ONLY for the owner's response (e.g., comments, date corrected).
 * - Provide an upload component for owners to submit proof of correction photos.
 * - Ensure robust error handling if decryption fails or data is malformed (show "Invalid or expired link" error).
 */
import CryptoJS from 'crypto-js';

// In a real production environment, ensure this matches the environment variable on avria.cloud
const SECRET_KEY = import.meta.env.VITE_QR_ENCRYPTION_KEY || 'avria-secure-qr-fallback-key-2026';

/**
 * Encrypts violation data into a URL-safe Base64 encoded string.
 * @param {Object} dataObj The violation details to encrypt.
 * @returns {string|null} The encrypted, URL-safe string or null if encryption fails.
 */
export function encryptViolationData(dataObj) {
    try {
        const jsonStr = JSON.stringify(dataObj);
        const encrypted = CryptoJS.AES.encrypt(jsonStr, SECRET_KEY).toString();
        // Make Base64 URL safe for query parameters
        return encrypted.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
    } catch (error) {
        console.error("Encryption failed:", error);
        return null;
    }
}

/**
 * Decrypts a URL-safe Base64 encoded string back into the violation data object.
 * @param {string} encodedStr The encrypted string from the URL.
 * @returns {Object|null} The decrypted data object or null if decryption fails.
 */
export function decryptViolationData(encodedStr) {
    try {
        // Restore standard Base64 characters
        let base64 = encodedStr.replace(/-/g, '+').replace(/_/g, '/');
        // Pad with '=' to make length a multiple of 4
        while (base64.length % 4) {
            base64 += '=';
        }
        const bytes = CryptoJS.AES.decrypt(base64, SECRET_KEY);
        const decryptedStr = bytes.toString(CryptoJS.enc.Utf8);
        
        if (!decryptedStr) return null;
        
        return JSON.parse(decryptedStr);
    } catch (error) {
        console.error("Decryption failed:", error);
        return null;
    }
}