package com.secureline.notes.export;

import android.content.Context;

import com.secureline.notes.BuildConfig;
import com.secureline.notes.crypto.CryptoManager;
import com.secureline.notes.data.Note;
import com.secureline.notes.data.NotesRepository;

import org.json.JSONArray;
import org.json.JSONObject;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class ExportManager {

    private static final int MAX_NOTES = 500;
    private static final int MAX_TEXT_LENGTH = 10000;
    private static final int MAX_EXPORT_JSON_SIZE = 6 * 1024 * 1024; // hard safety cap

    public static byte[] buildExport(
            Context ctx,
            String password
    ) throws Exception {

        if (ctx == null)
            throw new IllegalArgumentException("context null");

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

        NotesRepository repo = new NotesRepository(ctx);

        List<Note> notes = repo.getAll();

        if (notes == null)
            throw new IllegalStateException("notes null");

        if (notes.size() > MAX_NOTES)
            throw new IllegalStateException("too many notes");

        JSONObject root = new JSONObject();

        root.put("format", "lemenzo_notes");
        root.put("version", 1);
        root.put("created", System.currentTimeMillis());

        JSONArray arr = new JSONArray();

	for (Note n : notes) {
	    if (n == null) continue;

	    try {
	        JSONObject obj = new JSONObject();

	        obj.put("title", safeText(n.title));
	        obj.put("content", safeText(n.content));
	        obj.put("updated", n.updated);

	        arr.put(obj);

	    } catch (Exception e) {
	        if (BuildConfig.DEBUG) {
	            e.printStackTrace();
	        }
	    }
	}

	root.put("notes", arr);

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

	if (jsonBytes.length == 0 || jsonBytes.length > MAX_EXPORT_JSON_SIZE)
	    throw new IllegalStateException("export too large");

	byte[] encrypted = CryptoManager.encryptExport(jsonBytes, password);

	// 🔒 wipe plaintext JSON (vigtigt)
	for (int i = 0; i < jsonBytes.length; i++) {
	    jsonBytes[i] = 0;
	}

	return encrypted;
    }

    private static String safeText(String input) {
        if (input == null) return "";

        if (input.length() > MAX_TEXT_LENGTH) {
            return input.substring(0, MAX_TEXT_LENGTH);
        }

        return input;
    }
}
