-- AppView migration 0004: like/repost counter cache + uniqueness
--
-- Phase 5b review identified two issues:
--   H3 — Users could spam `feed.like.create` against the same post because
--         the `likes` PK is just `uri` (the like's own rkey). Adding a
--         partial unique index lets us short-circuit "already liked" at the
--         DB layer instead of relying on caller discipline.
--   H6 — `SELECT COUNT(*) FROM likes WHERE post_uri = $1` on every post fetch
--         doesn't scale. We add a denormalized counter on `posts` that's
--         kept consistent by the AppView's own ingest path. Jetstream-driven
--         upserts touch this too. The PDS path goes through ingest-commit
--         which routes through the same code.
--
-- Idempotent: dedup likes/reposts first (real-world Jetstream replays can
-- leave duplicates). Keep only the oldest row per (did, post_uri).

-- dedup likes: keep only the lowest uri per (did, post_uri)
DELETE FROM likes a USING likes b
 WHERE a.did = b.did
   AND a.post_uri = b.post_uri
   AND a.uri > b.uri;

-- dedup reposts: same approach
DELETE FROM reposts a USING reposts b
 WHERE a.did = b.did
   AND a.post_uri = b.post_uri
   AND a.uri > b.uri;

CREATE UNIQUE INDEX IF NOT EXISTS likes_did_post_uri_idx
    ON likes (did, post_uri);

CREATE UNIQUE INDEX IF NOT EXISTS reposts_did_post_uri_idx
    ON reposts (did, post_uri);

ALTER TABLE posts ADD COLUMN IF NOT EXISTS like_count    BIGINT NOT NULL DEFAULT 0;
ALTER TABLE posts ADD COLUMN IF NOT EXISTS repost_count  BIGINT NOT NULL DEFAULT 0;

-- Backfill: compute current counts from the now-deduped rows so the
-- column matches reality on upgrade. Wrapped in a single statement so
-- it's fast even on 100k+ rows.
UPDATE posts p
   SET like_count   = COALESCE((SELECT COUNT(*) FROM likes    WHERE post_uri = p.uri), 0),
       repost_count = COALESCE((SELECT COUNT(*) FROM reposts  WHERE post_uri = p.uri), 0);

CREATE INDEX IF NOT EXISTS posts_count_idx ON posts (like_count DESC, repost_count DESC);