package com.secureline.notes.export;

import com.secureline.notes.crypto.CryptoManager;

import org.json.JSONObject;

import java.nio.charset.StandardCharsets;

public class ExportSingleNoteManager {

    private static final int MAX_EXPORT_SIZE = 6 * 1024 * 1024;

    public static byte[] buildSingleNote(
            String title,
            String content,
            String password
    ) throws Exception {

        if (password == null || password.length() < 8)
            throw new IllegalArgumentException("weak password");

        JSONObject root = new JSONObject();

        root.put("format", "lzn_note");
        root.put("version", 1);
        root.put("created", System.currentTimeMillis());
        root.put("title", title == null ? "" : title);
        root.put("content", content == null ? "" : content);

        byte[] jsonBytes = root.toString().getBytes(StandardCharsets.UTF_8);

        // ✅ FIX: size protection
        if (jsonBytes.length == 0 || jsonBytes.length > MAX_EXPORT_SIZE)
            throw new IllegalStateException("export too large");

        try {
            return CryptoManager.encryptExport(jsonBytes, password);
        } finally {
            for (int i = 0; i < jsonBytes.length; i++) {
                jsonBytes[i] = 0;
            }
        }
    }
}
