-- pgTAP: search_vectors — generated tsvector columns + GIN indexes + function — Fase 4
-- Run with: psql -U postgres -d postgres -f supabase/tests/007_search_tsvector.sql

CREATE EXTENSION IF NOT EXISTS pgtap;

BEGIN;
SELECT plan(9);

-- Column existence — stored generated tsvector
SELECT has_column('public', 'shopping_items', 'search',
    'SV-01: shopping_items.search column exists');
SELECT has_column('public', 'tasks', 'search',
    'SV-02: tasks.search column exists');
SELECT has_column('public', 'notes', 'search',
    'SV-03: notes.search column exists');

-- GIN indexes present
SELECT ok(
    EXISTS (
        SELECT 1 FROM pg_indexes
        WHERE schemaname = 'public' AND tablename = 'shopping_items' AND indexname = 'shopping_items_search_idx'
    ),
    'SV-04: shopping_items_search_idx GIN index exists'
);

SELECT ok(
    EXISTS (
        SELECT 1 FROM pg_indexes
        WHERE schemaname = 'public' AND tablename = 'tasks' AND indexname = 'tasks_search_idx'
    ),
    'SV-05: tasks_search_idx GIN index exists'
);

SELECT ok(
    EXISTS (
        SELECT 1 FROM pg_indexes
        WHERE schemaname = 'public' AND tablename = 'notes' AND indexname = 'notes_search_idx'
    ),
    'SV-06: notes_search_idx GIN index exists'
);

-- Function exists and is callable
SELECT has_function('public', 'search_in_collective',
    ARRAY['uuid', 'text', 'public.search_result_type[]', 'uuid', 'timestamptz', 'timestamptz'],
    'SV-07: search_in_collective(uuid, text, types[], creator, from, to) exists');

-- Functional invariants on the generated vector: insert an item, vector reflects the name
DO $$
DECLARE
    v_item_id uuid;
    v_vector  tsvector;
BEGIN
    INSERT INTO public.shopping_items (list_id, name, sort_order, created_by)
    VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'pgtap unique xyzzy', 9998,
            '11111111-1111-1111-1111-111111111111')
    RETURNING id INTO v_item_id;

    SELECT search INTO v_vector FROM public.shopping_items WHERE id = v_item_id;
    PERFORM set_config('pgtap.vector_text', v_vector::text, false);
    PERFORM set_config('pgtap.vector_match',
        CASE WHEN v_vector @@ to_tsquery('simple', 'xyzzy') THEN 'true' ELSE 'false' END,
        false);
END $$;

SELECT matches(
    current_setting('pgtap.vector_text'),
    'xyzzy',
    'SV-08: generated shopping_items.search vector contains the inserted lexeme'
);

SELECT is(
    current_setting('pgtap.vector_match'),
    'true',
    'SV-09: generated shopping_items.search vector matches its tsquery'
);

SELECT * FROM finish();
ROLLBACK;
