-- RTGS 계층 대사 리포트 (S1 정합성).
-- 실행: psql -h localhost -p 5433 -U rtgs -d rtgs -f reconcile.sql
\pset border 2
\echo ''
\echo '== 1) 계좌 총액 (보존 불변식: 이체 전후 항상 동일해야 함) =='
SELECT sum(balance) AS total_balance, count(*) AS accounts FROM account;

\echo '== 2) 거래 상태 분포 =='
SELECT status, count(*) AS cnt FROM transfer GROUP BY status ORDER BY status;

\echo '== 3) 미완결 잔류 (ACSP/PDNG에 머문 건 = 있으면 이상) =='
SELECT count(*) AS stuck FROM transfer WHERE status IN ('PDNG','ACSP');

\echo '== 4) 원장 vs 조회사본 대사 (ACCC 건수 일치해야) =='
SELECT (SELECT count(*) FROM transfer        WHERE status='ACCC')       AS ledger_accc,
       (SELECT count(*) FROM settlement_view WHERE final_status='ACCC') AS view_accc;

\echo '== 5) 선저널 대사 (정산건 <= journal_log 기록건) =='
SELECT (SELECT count(*) FROM transfer WHERE status IN ('ACSP','ACCC')) AS settled,
       (SELECT count(*) FROM journal_log)                              AS journal_rows;

\echo '== 6) 잔액 음수 계좌 (있으면 이중지급/오류) =='
SELECT count(*) AS negative_accounts FROM account WHERE balance < 0;
\echo ''
