/**
 * Local storage layer for Android/WebView — uses IndexedDB instead of SQLite.
 * Implements the subset of MailxDB that the client needs.
 */
const DB_NAME = "rmfmail";
const DB_VERSION = 1;
let db = null;
async function openDB() {
    if (db)
        return db;
    return new Promise((resolve, reject) => {
        const req = indexedDB.open(DB_NAME, DB_VERSION);
        req.onupgradeneeded = () => {
            const d = req.result;
            if (!d.objectStoreNames.contains("accounts")) {
                d.createObjectStore("accounts", { keyPath: "id" });
            }
            if (!d.objectStoreNames.contains("folders")) {
                const fs = d.createObjectStore("folders", { keyPath: "id", autoIncrement: true });
                fs.createIndex("accountId", "accountId");
            }
            if (!d.objectStoreNames.contains("messages")) {
                const ms = d.createObjectStore("messages", { keyPath: "key" });
                ms.createIndex("accountId", "accountId");
                ms.createIndex("folderId", "folderId");
                ms.createIndex("folder", ["accountId", "folderId"]);
                ms.createIndex("date", "date");
            }
            if (!d.objectStoreNames.contains("bodies")) {
                d.createObjectStore("bodies", { keyPath: "key" });
            }
            if (!d.objectStoreNames.contains("contacts")) {
                const cs = d.createObjectStore("contacts", { keyPath: "email" });
                cs.createIndex("name", "name");
            }
            if (!d.objectStoreNames.contains("meta")) {
                d.createObjectStore("meta", { keyPath: "key" });
            }
        };
        req.onsuccess = () => { db = req.result; resolve(db); };
        req.onerror = () => reject(req.error);
    });
}
function tx(stores, mode = "readonly") {
    const names = Array.isArray(stores) ? stores : [stores];
    return db.transaction(names, mode);
}
function getAll(store, index, key) {
    return new Promise((resolve, reject) => {
        const t = tx(store);
        const s = t.objectStore(store);
        const target = index ? s.index(index) : s;
        const req = key ? target.getAll(key) : target.getAll();
        req.onsuccess = () => resolve(req.result);
        req.onerror = () => reject(req.error);
    });
}
function put(store, value) {
    return new Promise((resolve, reject) => {
        const t = tx(store, "readwrite");
        t.objectStore(store).put(value);
        t.oncomplete = () => resolve();
        t.onerror = () => reject(t.error);
    });
}
function del(store, key) {
    return new Promise((resolve, reject) => {
        const t = tx(store, "readwrite");
        t.objectStore(store).delete(key);
        t.oncomplete = () => resolve();
        t.onerror = () => reject(t.error);
    });
}
// ── Public API (mirrors MailxDB methods used by the client service) ──
export async function init() {
    await openDB();
}
export async function getAccounts() {
    return getAll("accounts");
}
export async function upsertAccount(id, name, email, config) {
    await put("accounts", { id, name, email, config, lastSync: 0 });
}
export async function getFolders(accountId) {
    return getAll("folders", "accountId", accountId);
}
export async function upsertFolder(folder) {
    await put("folders", folder);
}
export async function getMessages(accountId, folderId, page = 1, pageSize = 50) {
    const all = await getAll("messages", "folder", [accountId, folderId]);
    // Sort by date descending
    all.sort((a, b) => b.date - a.date);
    const total = all.length;
    const start = (page - 1) * pageSize;
    const items = all.slice(start, start + pageSize).map(toEnvelope);
    return { items, total, page, pageSize };
}
export async function getUnifiedInbox(page = 1, pageSize = 50) {
    const folders = await getAll("folders");
    const inboxFolders = folders.filter(f => f.specialUse === "inbox");
    const allMsgs = [];
    for (const f of inboxFolders) {
        const msgs = await getAll("messages", "folder", [f.accountId, f.id]);
        allMsgs.push(...msgs);
    }
    allMsgs.sort((a, b) => b.date - a.date);
    const total = allMsgs.length;
    const start = (page - 1) * pageSize;
    const items = allMsgs.slice(start, start + pageSize).map(toEnvelope);
    return { items, total, page, pageSize };
}
export async function getMessageByUid(accountId, uid, folderId) {
    if (folderId != null) {
        const key = `${accountId}:${folderId}:${uid}`;
        return new Promise((resolve, reject) => {
            const t = tx("messages");
            const req = t.objectStore("messages").get(key);
            req.onsuccess = () => resolve(req.result ? toEnvelope(req.result) : null);
            req.onerror = () => reject(req.error);
        });
    }
    // Search all folders
    const all = await getAll("messages", "accountId", accountId);
    const msg = all.find(m => m.uid === uid);
    return msg ? toEnvelope(msg) : null;
}
export async function upsertMessage(msg) {
    await put("messages", msg);
}
export async function deleteMessage(accountId, uid) {
    const all = await getAll("messages", "accountId", accountId);
    const msg = all.find(m => m.uid === uid);
    if (msg)
        await del("messages", msg.key);
}
export async function getHighestUid(accountId, folderId) {
    const msgs = await getAll("messages", "folder", [accountId, folderId]);
    return msgs.reduce((max, m) => Math.max(max, m.uid), 0);
}
export async function getBody(accountId, folderId, uid) {
    return new Promise((resolve, reject) => {
        const t = tx("bodies");
        const req = t.objectStore("bodies").get(`${accountId}:${folderId}:${uid}`);
        req.onsuccess = () => resolve(req.result?.body || null);
        req.onerror = () => reject(req.error);
    });
}
export async function updateFolderCounts(folderId, total, unread) {
    const folders = await getAll("folders");
    const f = folders.find(f => f.id === folderId);
    if (f) {
        f.totalCount = total;
        f.unreadCount = unread;
        await put("folders", f);
    }
}
export async function searchContacts(query) {
    const q = query.toLowerCase();
    const all = await getAll("contacts");
    return all.filter(c => c.name.toLowerCase().includes(q) || c.email.toLowerCase().includes(q)).slice(0, 10);
}
export async function upsertContact(email, name, source) {
    const existing = await new Promise((resolve, reject) => {
        const t = tx("contacts");
        const req = t.objectStore("contacts").get(email);
        req.onsuccess = () => resolve(req.result);
        req.onerror = () => reject(req.error);
    });
    if (existing) {
        existing.useCount++;
        existing.lastUsed = Date.now();
        if (name && !existing.name)
            existing.name = name;
        await put("contacts", existing);
    }
    else {
        await put("contacts", { email, name, source, useCount: 1, lastUsed: Date.now() });
    }
}
export async function getMeta(key) {
    return new Promise((resolve, reject) => {
        const t = tx("meta");
        const req = t.objectStore("meta").get(key);
        req.onsuccess = () => resolve(req.result?.value);
        req.onerror = () => reject(req.error);
    });
}
export async function setMeta(key, value) {
    await put("meta", { key, value });
}
// ── Helpers ──
function toEnvelope(m) {
    return {
        accountId: m.accountId,
        folderId: m.folderId,
        uid: m.uid,
        messageId: m.messageId,
        date: m.date,
        subject: m.subject,
        from: { name: m.fromName, address: m.fromAddress },
        to: JSON.parse(m.toJson || "[]"),
        cc: JSON.parse(m.ccJson || "[]"),
        flags: m.flags ? m.flags.split(",").filter(Boolean) : [],
        size: m.size,
        hasAttachments: m.hasAttachments,
        preview: m.preview,
        bodyPath: m.bodyPath,
    };
}
//# sourceMappingURL=local-store.js.map