-- Test Script for Migration 019: PostgreSQL NOTIFY Triggers
--
-- How to use:
-- 1. Run this in one psql terminal: psql -U postgres -d foxhunt -f 019_test_notify.sql
-- 2. Open another psql terminal and run the test queries below
--
-- Or use multiple tmux/screen sessions for interactive testing

-- ============================================================================
-- Test 1: Config Entry Changes - Service-Specific Routing
-- ============================================================================

-- Expected behavior:
-- - Risk config changes → config_changed_trading
-- - ML config changes → config_changed_ml_training
-- - Backtesting config → config_changed_backtesting
-- - All changes → config_changed_global

\echo '=== Test 1: Risk Configuration Change (Trading Service) ==='
\echo 'Run in another terminal: LISTEN config_changed_trading;'
\echo 'Then execute this update...'

-- Simulate risk configuration update
UPDATE config_entries
SET value = '150000'
WHERE key LIKE 'risk.%'
LIMIT 1;

\echo 'Expected: NOTIFY on config_changed_trading channel'
\echo ''

\echo '=== Test 2: ML Configuration Change (ML Training Service) ==='
\echo 'Run in another terminal: LISTEN config_changed_ml_training;'

-- Simulate ML configuration update
UPDATE config_entries
SET value = '7200'
WHERE key LIKE 'ml.%'
LIMIT 1;

\echo 'Expected: NOTIFY on config_changed_ml_training channel'
\echo ''

\echo '=== Test 3: Global Monitoring Channel ==='
\echo 'Run in another terminal: LISTEN config_changed_global;'

-- Any config change should trigger global notification
UPDATE config_entries
SET value = '15'
WHERE key LIKE 'system.%'
LIMIT 1;

\echo 'Expected: NOTIFY on config_changed_global channel'
\echo ''

-- ============================================================================
-- Test 2: Model Configuration Changes - Multi-Channel
-- ============================================================================

\echo '=== Test 4: Model Configuration Change (ML + Trading) ==='
\echo 'Run in terminal 1: LISTEN config_changed_ml_training;'
\echo 'Run in terminal 2: LISTEN config_changed_trading;'

-- Insert test model config
INSERT INTO model_config (name, version, s3_path, metadata, is_active)
VALUES (
    'test_mamba2',
    'v1.0.0',
    's3://foxhunt-models/test/mamba2-v1.0.0.bin',
    '{"model_type": "mamba2", "test": true}',
    false
)
ON CONFLICT (name, version) DO UPDATE
SET is_active = NOT model_config.is_active;

\echo 'Expected: NOTIFY on BOTH config_changed_ml_training AND config_changed_trading'
\echo ''

-- ============================================================================
-- Test 3: Permission Changes - RBAC
-- ============================================================================

\echo '=== Test 5: Permission Change (API Gateway) ==='
\echo 'Run in another terminal: LISTEN permissions_changed;'

-- Grant new permission to trader role
DO $$
DECLARE
    trader_role_id UUID;
    view_risk_perm_id UUID;
BEGIN
    -- Get trader role ID
    SELECT id INTO trader_role_id FROM roles WHERE name = 'trader';

    -- Get risk.view_metrics permission ID
    SELECT id INTO view_risk_perm_id FROM permissions WHERE endpoint = 'risk.view_metrics';

    -- Remove and re-add permission to trigger NOTIFY
    DELETE FROM role_permissions
    WHERE role_id = trader_role_id AND permission_id = view_risk_perm_id;

    INSERT INTO role_permissions (role_id, permission_id)
    VALUES (trader_role_id, view_risk_perm_id);

    RAISE NOTICE 'Permission change executed - check NOTIFY listener';
END $$;

\echo 'Expected: NOTIFY on permissions_changed channel'
\echo ''

-- ============================================================================
-- Test 4: Payload Verification
-- ============================================================================

\echo '=== Test 6: Verify Payload Structure ==='
\echo 'Run in another terminal:'
\echo '  LISTEN config_changed_trading;'
\echo 'Then check the payload contains:'
\echo '  - operation: UPDATE'
\echo '  - table: config_entries'
\echo '  - key: risk.max_daily_loss'
\echo '  - value: <new value>'
\echo '  - old_value: <old value>'
\echo '  - category: risk'
\echo '  - timestamp: <epoch timestamp>'
\echo ''

-- Trigger a well-structured notification
UPDATE config_entries
SET value = '200000'
WHERE key = 'risk.max_daily_loss';

\echo 'Payload verification complete'
\echo ''

-- ============================================================================
-- Test 5: Multiple Services Listening
-- ============================================================================

\echo '=== Test 7: Multiple Services Receiving Same Notification ==='
\echo 'Run in terminal 1: LISTEN config_changed_trading;'
\echo 'Run in terminal 2: LISTEN config_changed_global;'
\echo ''
\echo 'A single UPDATE should trigger BOTH listeners:'

UPDATE config_entries
SET value = '0.96'
WHERE key = 'risk.var_confidence';

\echo 'Expected: NOTIFY received by both terminals'
\echo ''

-- ============================================================================
-- Summary and Next Steps
-- ============================================================================

\echo '========================================='
\echo 'Test Summary'
\echo '========================================='
\echo ''
\echo 'Channels to test:'
\echo '  1. config_changed_trading'
\echo '  2. config_changed_ml_training'
\echo '  3. config_changed_backtesting'
\echo '  4. config_changed_api_gateway'
\echo '  5. config_changed_global'
\echo '  6. permissions_changed'
\echo ''
\echo 'Test Scenarios:'
\echo '  ✓ Risk config → trading channel'
\echo '  ✓ ML config → ml_training channel'
\echo '  ✓ System config → global channel'
\echo '  ✓ Model config → ml_training + trading channels'
\echo '  ✓ Permission change → permissions_changed channel'
\echo ''
\echo 'Interactive Testing Command:'
\echo '  psql -U postgres -d foxhunt'
\echo '  > LISTEN config_changed_trading;'
\echo '  > (in another terminal) UPDATE config_entries SET value=''999'' WHERE key=''risk.max_daily_loss'';'
\echo ''

-- ============================================================================
-- Cleanup Test Data
-- ============================================================================

-- Remove test model config
DELETE FROM model_config WHERE name = 'test_mamba2' AND metadata->>'test' = 'true';

\echo 'Test data cleaned up'
