-- Scan job progress + mailbox attribution on discovered profiles.

ALTER TABLE contact_discovery_scans
    ADD COLUMN IF NOT EXISTS total_messages INT NOT NULL DEFAULT 0,
    ADD COLUMN IF NOT EXISTS phase TEXT NOT NULL DEFAULT 'pending',
    ADD COLUMN IF NOT EXISTS book_id TEXT NOT NULL DEFAULT 'contacts',
    ADD COLUMN IF NOT EXISTS nc_user_id TEXT NOT NULL DEFAULT '',
    ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW();

ALTER TABLE contact_discovered_profiles
    ADD COLUMN IF NOT EXISTS detected_in_accounts JSONB NOT NULL DEFAULT '[]';

CREATE INDEX IF NOT EXISTS idx_contact_discovery_scans_active
    ON contact_discovery_scans(user_id, status)
    WHERE status IN ('pending', 'running');
