-- pgTAP: Realtime publication + replica identity — Fase 2b prep
-- Run with: psql -U postgres -d postgres -f supabase/tests/004_realtime_publication.sql
--
-- These invariants must hold for Supabase Realtime to forward Postgres Changes
-- events for shopping_items / shopping_lists to subscribed clients with the
-- correct row payloads. Breaking any of them silently drops events.

CREATE EXTENSION IF NOT EXISTS pgtap;

BEGIN;
SELECT plan(4);

-- P-01: shopping_items is in the supabase_realtime publication
SELECT ok(
    EXISTS (
        SELECT 1 FROM pg_publication_tables
        WHERE pubname = 'supabase_realtime'
        AND   schemaname = 'public'
        AND   tablename = 'shopping_items'
    ),
    'P-01: shopping_items is part of the supabase_realtime publication'
);

-- P-02: shopping_lists is in the supabase_realtime publication
SELECT ok(
    EXISTS (
        SELECT 1 FROM pg_publication_tables
        WHERE pubname = 'supabase_realtime'
        AND   schemaname = 'public'
        AND   tablename = 'shopping_lists'
    ),
    'P-02: shopping_lists is part of the supabase_realtime publication'
);

-- P-03: shopping_items has REPLICA IDENTITY FULL so UPDATE/DELETE events
-- carry the full row (needed for list_id-based client filtering and RLS on DELETE)
SELECT results_eq(
    $$ SELECT relreplident::text FROM pg_class c
       JOIN   pg_namespace n ON n.oid = c.relnamespace
       WHERE  n.nspname = 'public' AND c.relname = 'shopping_items' $$,
    $$ VALUES ('f') $$,
    'P-03: shopping_items has REPLICA IDENTITY FULL'
);

-- P-04: same for shopping_lists
SELECT results_eq(
    $$ SELECT relreplident::text FROM pg_class c
       JOIN   pg_namespace n ON n.oid = c.relnamespace
       WHERE  n.nspname = 'public' AND c.relname = 'shopping_lists' $$,
    $$ VALUES ('f') $$,
    'P-04: shopping_lists has REPLICA IDENTITY FULL'
);

SELECT * FROM finish();
ROLLBACK;
