export const TABLES = [
    `CREATE TABLE IF NOT EXISTS accounts (
        public_key TEXT PRIMARY KEY,
        private_key TEXT NOT NULL,
        sfen TEXT NOT NULL,
        UNIQUE (public_key)
    )`,

    `CREATE TABLE IF NOT EXISTS blacklist (
        id INTEGER PRIMARY KEY,
        public_key TEXT NOT NULL,
        account TEXT NOT NULL
    )`,

    `CREATE TABLE IF NOT EXISTS avatar_delivery (
        id INTEGER PRIMARY KEY,
        public_key TEXT NOT NULL,
        account TEXT NOT NULL
    )`,

    `CREATE TABLE IF NOT EXISTS avatar_cache (
        id INTEGER PRIMARY KEY,
        public_key TEXT,
        avatar TEXT NOT NULL,
        timestamp INTEGER NOT NULL,
        UNIQUE (id)
    )`,

    `CREATE TABLE IF NOT EXISTS messages (
        id INTEGER PRIMARY KEY,
        account TEXT NOT NULL,
        from_public_key TEXT NOT NULL,
        to_public_key BLOB NOT NULL,
        content BLOB NOT NULL,
        timestamp INTEGER NOT NULL,
        chacha_key BLOB NOT NULL,
        read INTEGER NOT NULL DEFAULT 0,
        from_me INTEGER NOT NULL DEFAULT 0,
        delivered INTEGER NOT NULL DEFAULT 0,
        message_id TEXT NOT NULL DEFAULT '',
        plain_message BLOB NOT NULL,
        attachments TEXT NOT NULL DEFAULT '[]',
        UNIQUE (id)
    )`,
    
    /**
     * Создаем индекс на столбцы message_id и public_key чтобы избежать дубликации сообщений при синхронизации
     */
    `CREATE UNIQUE INDEX IF NOT EXISTS idx_messages_message_id_public_key ON messages(message_id, account)`,

    `CREATE TABLE IF NOT EXISTS cached_users (
        public_key TEXT PRIMARY KEY,
        title TEXT NOT NULL,
        username TEXT NOT NULL,
        verified INTEGER NOT NULL DEFAULT 0,
        UNIQUE (public_key)
    )`,
    
    `CREATE TABLE IF NOT EXISTS groups (
        id INTEGER PRIMARY KEY,
        account TEXT NOT NULL,
        group_id TEXT NOT NULL,
        title TEXT NOT NULL,
        description TEXT NOT NULL,
        key TEXT NOT NULL,
        UNIQUE (id)
    )`,
    /**
     * dialog_id can be a public key for individual chats or a group ID for group chats
     * last_message encoded with private key of the account
     * last_message_from is the public key of the sender
     */
    `CREATE TABLE IF NOT EXISTS dialogs (
        id INTEGER PRIMARY KEY,
        account TEXT NOT NULL,
        dialog_id TEXT NOT NULL,
        last_message_id TEXT NOT NULL,
        last_timestamp INTEGER NOT NULL,
        is_request INTEGER NOT NULL DEFAULT 0,
        UNIQUE (id)
    )`,
    /** 
     * Таблица для хранения времени последней синхронизации сообщений
     * last_sync время отключения клиента от сервера
     */
    `CREATE TABLE IF NOT EXISTS accounts_sync_times (
        id INTEGER PRIMARY KEY,
        account TEXT NOT NULL,
        last_sync INTEGER NOT NULL,
        UNIQUE (account)
    )`
]