CREATE TABLE ias_mail_accounts (
    id BIGSERIAL PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    source_key VARCHAR(512) NOT NULL UNIQUE,
    imap_host VARCHAR(255) NOT NULL,
    imap_port INTEGER NOT NULL DEFAULT 993,
    imap_username TEXT NOT NULL,
    imap_password TEXT NOT NULL,
    mailbox VARCHAR(255) NOT NULL DEFAULT 'INBOX',
    notify_account_id VARCHAR(255) NOT NULL,
    notify_user_id VARCHAR(255) NOT NULL,
    poll_seconds INTEGER NOT NULL DEFAULT 60,
    fetch_limit INTEGER NOT NULL DEFAULT 10,
    accept_invalid_certs BOOLEAN NOT NULL DEFAULT FALSE,
    enabled BOOLEAN NOT NULL DEFAULT TRUE,
    last_checked_at TIMESTAMPTZ,
    last_error TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_ias_mail_accounts_enabled
    ON ias_mail_accounts(enabled, id);

ALTER TABLE ias_mail_messages
    ADD COLUMN mail_account_id BIGINT REFERENCES ias_mail_accounts(id) ON DELETE SET NULL,
    ADD COLUMN content TEXT NOT NULL DEFAULT '',
    ADD COLUMN raw_headers TEXT;

CREATE INDEX idx_ias_mail_messages_account
    ON ias_mail_messages(mail_account_id, created_at DESC);

INSERT INTO ias_upgrade_logs (
    version,
    released_at,
    title,
    description,
    changes
) VALUES (
    '0.1.5',
    '2026-07-06T00:00:00+08:00',
    'Database-backed mail auth and cache',
    'Added guided mail account configuration with ias mail auth, persisted mail accounts in the database, and expanded mail message caching.',
    '[
        "Added database-backed mail account configuration through the guided ias mail auth command.",
        "Added the ias_mail_accounts table and linked cached mail messages back to their configured account.",
        "Extended the mail cache to persist full parsed mail content and raw headers in ias_mail_messages.",
        "Updated mail polling to load enabled mail accounts from the database first, while keeping environment-based configuration as a fallback.",
        "Added mail account listing through ias mail list.",
        "Persisted the 0.1.5 upgrade record."
    ]'::jsonb
) ON CONFLICT (version) DO UPDATE SET
    released_at = EXCLUDED.released_at,
    title = EXCLUDED.title,
    description = EXCLUDED.description,
    changes = EXCLUDED.changes;
