-- Test Query: Simuliert den Sync Query
-- Führe diese Query aus um zu sehen, welche Daten synchronisiert werden

-- 1. Zeige Anzahl der Transaktionen mit status='done'
SELECT
    'backend.transactions (done)' as table_name,
    COUNT(*) as record_count
FROM backend.transactions
WHERE status = 'done'

UNION ALL

-- 2. Zeige Anzahl der transaction_outputs für 'done' Transaktionen
SELECT
    'backend.transaction_outputs (for done transactions)' as table_name,
    COUNT(*) as record_count
FROM backend.transaction_outputs tout
JOIN backend.transactions t ON t.id = tout.transaction_id
WHERE t.status = 'done'

UNION ALL

-- 3. Zeige JOIN Resultat (das wird synchronisiert)
SELECT
    'JOIN Result (will be synced)' as table_name,
    COUNT(*) as record_count
FROM backend.transactions t
LEFT JOIN backend.transaction_outputs tout ON t.id = tout.transaction_id
WHERE t.status = 'done';

-- ==========================================

-- 4. Zeige erste 5 Datensätze die synchronisiert werden
SELECT
    t.id as transaction_id,
    t.corporate_entity,
    t.corporate_counterparty,
    t.tx_date,
    t.tx_amount,
    t.tx_currency,
    t.status,
    tout.prompt_id,
    tout.output_key,
    LEFT(tout.content, 100) as content_preview,
    tout.run_id
FROM backend.transactions t
LEFT JOIN backend.transaction_outputs tout ON t.id = tout.transaction_id
WHERE t.status = 'done'
ORDER BY t.id, tout.prompt_id
LIMIT 5;

-- ==========================================

-- 5. Zeige Verteilung der output_keys
SELECT
    tout.output_key,
    COUNT(*) as count
FROM backend.transaction_outputs tout
JOIN backend.transactions t ON t.id = tout.transaction_id
WHERE t.status = 'done'
GROUP BY tout.output_key
ORDER BY count DESC
LIMIT 20;

-- ==========================================

-- 6. Zeige Transactions ohne Outputs (LEFT JOIN NULL)
SELECT
    t.id,
    t.corporate_entity,
    t.status
FROM backend.transactions t
LEFT JOIN backend.transaction_outputs tout ON t.id = tout.transaction_id
WHERE t.status = 'done'
    AND tout.transaction_id IS NULL
LIMIT 10;
