/**
 * 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;

interface StoredAccount {
    id: string;
    name: string;
    email: string;
    config: string;
    lastSync: number;
}

interface StoredFolder {
    id: number;
    accountId: string;
    path: string;
    delimiter: string;
    specialUse: string;
    totalCount: number;
    unreadCount: number;
}

interface StoredMessage {
    key: string; // accountId:folderId:uid
    accountId: string;
    folderId: number;
    uid: number;
    messageId: string;
    date: number;
    subject: string;
    fromName: string;
    fromAddress: string;
    toJson: string;
    ccJson: string;
    flags: string;
    size: number;
    hasAttachments: boolean;
    preview: string;
    bodyPath: string;
}

interface StoredBody {
    key: string; // accountId:folderId:uid
    body: string; // raw .eml source
}

interface StoredContact {
    email: string;
    name: string;
    source: string;
    useCount: number;
    lastUsed: number;
}

let db: IDBDatabase | null = null;

async function openDB(): Promise<IDBDatabase> {
    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: string | string[], mode: IDBTransactionMode = "readonly"): IDBTransaction {
    const names = Array.isArray(stores) ? stores : [stores];
    return db!.transaction(names, mode);
}

function getAll<T>(store: string, index?: string, key?: IDBValidKey | IDBKeyRange): Promise<T[]> {
    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: string, value: any): Promise<void> {
    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: string, key: IDBValidKey): Promise<void> {
    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(): Promise<void> {
    await openDB();
}

export async function getAccounts(): Promise<StoredAccount[]> {
    return getAll("accounts");
}

export async function upsertAccount(id: string, name: string, email: string, config: string): Promise<void> {
    await put("accounts", { id, name, email, config, lastSync: 0 });
}

export async function getFolders(accountId: string): Promise<StoredFolder[]> {
    return getAll("folders", "accountId", accountId);
}

export async function upsertFolder(folder: StoredFolder): Promise<void> {
    await put("folders", folder);
}

export async function getMessages(accountId: string, folderId: number, page = 1, pageSize = 50): Promise<{ items: any[]; total: number; page: number; pageSize: number }> {
    const all = await getAll<StoredMessage>("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): Promise<{ items: any[]; total: number; page: number; pageSize: number }> {
    const folders = await getAll<StoredFolder>("folders");
    const inboxFolders = folders.filter(f => f.specialUse === "inbox");
    const allMsgs: StoredMessage[] = [];
    for (const f of inboxFolders) {
        const msgs = await getAll<StoredMessage>("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: string, uid: number, folderId?: number): Promise<any | null> {
    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<StoredMessage>("messages", "accountId", accountId);
    const msg = all.find(m => m.uid === uid);
    return msg ? toEnvelope(msg) : null;
}

export async function upsertMessage(msg: StoredMessage): Promise<void> {
    await put("messages", msg);
}

export async function deleteMessage(accountId: string, uid: number): Promise<void> {
    const all = await getAll<StoredMessage>("messages", "accountId", accountId);
    const msg = all.find(m => m.uid === uid);
    if (msg) await del("messages", msg.key);
}

export async function getHighestUid(accountId: string, folderId: number): Promise<number> {
    const msgs = await getAll<StoredMessage>("messages", "folder", [accountId, folderId]);
    return msgs.reduce((max, m) => Math.max(max, m.uid), 0);
}

export async function getBody(accountId: string, folderId: number, uid: number): Promise<string | null> {
    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: number, total: number, unread: number): Promise<void> {
    const folders = await getAll<StoredFolder>("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: string): Promise<StoredContact[]> {
    const q = query.toLowerCase();
    const all = await getAll<StoredContact>("contacts");
    return all.filter(c => c.name.toLowerCase().includes(q) || c.email.toLowerCase().includes(q)).slice(0, 10);
}

export async function upsertContact(email: string, name: string, source: string): Promise<void> {
    const existing = await new Promise<StoredContact | undefined>((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: string): Promise<any> {
    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: string, value: any): Promise<void> {
    await put("meta", { key, value });
}

// ── Helpers ──

function toEnvelope(m: StoredMessage): any {
    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,
    };
}
