-- Append-only change log for library entities. Every mutation on
-- artists/albums/tracks/likes/playlists/playlist_tracks writes a row
-- in the same transaction as the mutation itself. Powers the Flutter
-- delta-sync endpoint (#357) — clients pass back the last-seen `id`
-- as a cursor.
--
-- Retention: not capped here. If the table grows unbounded a follow-up
-- adds a periodic compactor (collapse contiguous upserts on the same
-- entity, drop pre-delete history). Cursor reset path (410) covers the
-- compactor's edge.

CREATE TABLE library_changes (
  id BIGSERIAL PRIMARY KEY,
  entity_type TEXT NOT NULL CHECK (entity_type IN (
    'artist', 'album', 'track', 'like_track', 'like_album', 'like_artist',
    'playlist', 'playlist_track'
  )),
  entity_id TEXT NOT NULL,
  op TEXT NOT NULL CHECK (op IN ('upsert', 'delete')),
  changed_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX idx_library_changes_id ON library_changes(id);
