-- AppView database migration 0002
-- Adds pagination indexes that support the keyset `(indexed_at DESC, uri DESC)`
-- ordered queries used by /api/timeline/home and /api/profile. Without these,
-- every page request triggers a full table scan + sort.
--
-- Also fixes an UPSERT bug: re-indexing the same post rewrote `indexed_at`,
-- which shifted the row in the pagination order and caused mid-pagination
-- users to silently skip or duplicate posts.

CREATE INDEX IF NOT EXISTS posts_collection_indexed_at_uri_idx
    ON posts (collection, indexed_at DESC, uri DESC);

CREATE INDEX IF NOT EXISTS posts_did_indexed_at_uri_idx
    ON posts (did, indexed_at DESC, uri DESC)
    WHERE collection IN ('app.twi.post','app.bsky.feed.post');